numpy-实战:用 NumPy 分析鸢尾花花萼属性各项指标

Posted by Hilda on July 20, 2025

实战 - 用 NumPy 分析鸢尾花花萼属性各项指标

本节将通过一个实际案例来展示如何使用 NumPy 对数据集进行基本的数据加载、清洗和统计分析。我们将使用经典的鸢尾花(Iris)数据集中的花萼长度数据。

1.数据加载与初步处理

  • 数据加载: np.loadtxt() 函数用于从文本文件加载数据。
    • fname:文件名或文件路径。
    • delimiter:指定文件中列之间的分隔符(例如,逗号 , 用于 CSV 文件,空格 ` ` 或制表符 \t 用于其他文本文件)。
    • dtype:指定加载数据的类型(例如 float)。
    • skiprows:跳过文件开头的行数(例如,跳过标题行)。
    • usecols:指定要加载的列的索引(从 0 开始)。
  • 数据结构: 加载后的数据通常是一个 NumPy 数组,其形状取决于文件中的行数和列数。
  • 初步处理:
    • 排序 (ndarray.sort()np.sort()): 对数据进行排序可以帮助我们更好地理解数据的分布,或为后续处理做准备。
    • 去重 (np.unique()): 找出数据中的唯一值,可以用于了解数据中不重复元素的种类。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import numpy as np
# csv文件,逗号是分隔符,所以用delimiter=","
data = np.loadtxt("./iris.csv", delimiter=",")
display(data.shape) # (150, 4)
# iris.csv 文件通常包含以下列
# sepal_length,sepal_width,petal_length,petal_width,species
# 我们只关心花萼(前2列),研究第1列
sepal_length = data[:, 0]
print(f"花萼长度数据:\n{sepal_length}") 
print(f"排序:\n{np.sort(sepal_length)}")
print(f"去重:\n{np.unique(sepal_length)}")
print(f"求和:\n{np.sum(sepal_length)}")
print(f"最大值:\n{np.max(sepal_length)}")
print(f"最小值:\n{np.min(sepal_length)}")
print(f"均值:\n{np.mean(sepal_length)}")
print(f"标准差:\n{np.std(sepal_length)}")
print(f"方差:\n{np.var(sepal_length)}")

image-20250720134231083

选择题

  1. 要从一个 CSV 文件 data.csv 中只读取第二列(假设是浮点数),并且跳过第一行标题,以下哪个 np.loadtxt 调用是正确的? A. np.loadtxt('data.csv', delimiter=',', usecols=1, skiprows=1, dtype=float)

    B. np.loadtxt('data.csv', delimiter=',', usecols=2, header=1, dtype=float)

    C. np.loadtxt('data.csv', separator=',', columns=1, skip_rows=1, type=float)

    D. np.loadtxt('data.csv', delimiter=',', usecols=1, skip_rows=1, dtype=float)

    答案:A

    usecols=1 表示第二列(索引从 0 开始)。

    skiprows=1 跳过第一行。

    delimiter=',' 指定逗号分隔符。

    dtype=float 指定数据类型。

  2. np.unique() 函数返回的数组有什么特点?

    A. 包含原始数组的所有元素,但顺序随机。

    B. 包含原始数组中所有重复的元素。

    C. 包含原始数组中所有唯一的元素,并且是排序的。

    D. 包含原始数组中所有唯一的元素,但顺序与原始数组相同。

    答案:C,np.unique() 的核心功能是去重并返回排序后的唯一元素。

编程题

  1. 创建一个模拟的 CSV 文件 sensor_data.csv,包含以下内容:

    1
    2
    3
    4
    5
    6
    
    timestamp,temperature,humidity
    1678886400,25.3,60.1
    1678886460,25.5,60.5
    1678886520,25.3,60.1
    1678886580,26.0,61.0
    1678886640,25.8,60.8
    
  2. 使用 np.loadtxt() 读取 sensor_data.csv 文件中的 temperature 列(第二列)。

  3. 对读取的温度数据进行排序。

  4. 找出所有唯一的温度值,并打印它们。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
data = np.loadtxt("./sensor_data.csv", delimiter=",", usecols=1, dtype=str, skiprows=0)
# data[0]是列的名字
data = data[1:].astype(float)
display(data)
"""
array([25.3, 25.5, 25.3, 26. , 25.8])
"""
# 排序
sorted_data = np.sort(data)
display(sorted_data)
"""
array([25.3, 25.3, 25.5, 25.8, 26. ])
"""
uni_data = np.unique(data)
display(uni_data)
"""
array([25.3, 25.5, 25.8, 26. ])
"""

2.数据分析与统计指标

在加载和初步处理数据后,通常需要计算各种统计指标来深入了解数据的特性。NumPy 提供了丰富的数学和统计函数来高效地完成这些任务。

  • 总和 (np.sum()): 计算数组中所有元素的总和。
  • 累积和 (np.cumsum()): 计算数组的累积和,即每个位置的元素是到该位置为止所有元素的和。
  • 均值 (np.mean()): 计算数组的算术平均值。
  • 标准差 (np.std()): 衡量数据点相对于均值的离散程度。
  • 方差 (np.var()): 标准差的平方,也是衡量数据离散程度的指标。
  • 最小值 (np.min()): 找出数组中的最小值。
  • 最大值 (np.max()): 找出数组中的最大值。

axis 参数的重要性: 对于多维数组,这些统计函数通常支持 axis 参数,允许您沿着特定的维度进行计算(例如,计算每列的均值或每行的总和)。

代码已经有了,都在上面。

选择题

  1. 给定 data = np.array([[1, 2, 3], [4, 5, 6]]),执行 np.mean(data, axis=1) 的结果是什么?

    A. array([2. , 5. ]) B. array([2.5, 3.5, 4.5]) C. array([3.5]) D. array([1. , 2. , 3. , 4. , 5. , 6. ])

    答案:A

    axis = 1,计算的是行的均值,所以A

  2. 以下哪个函数用于计算数组的累积乘积? A. np.sum() B. np.cumsum() C. np.prod() D. np.cumprod()

    答案:D

    np.cumprod() 计算累积乘积。

    np.sum() 计算总和。

    np.cumsum() 计算累积和。

    np.prod() 计算所有元素的乘积。

编程题

  1. 创建一个 10*3 的 NumPy 数组 student_scores,表示 10 名学生在 3 门课程上的分数(随机整数 50 到 100)。
  2. 计算并打印:
    • 所有学生所有课程的平均分。
    • 每门课程的最高分和最低分。
    • 每名学生的总分。
    • 每门课程分数的标准差。
  3. 假设 student_scores 的第一列是数学成绩。计算数学成绩的累积和。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
student_scores = np.random.randint(50, 101, (10, 3))
display(student_scores)
res1 = np.mean(student_scores, axis = 0)
print(f"所有课程的均分:{res1}")
max_res = np.max(student_scores, axis = 0)
min_res = np.min(student_scores, axis = 0)
print(f"所有课程的最高分:{max_res}, 最低分:{min_res}")
sum_res = np.sum(student_scores, axis = 1)
print(f"每名学生的总分:\n{sum_res}")
std = np.std(student_scores, axis = 0)
print(f"每门课程标准差:{std}")
cumsum_math = np.cumsum(student_scores[:,0])
print(f"数学成绩的累积和:{cumsum_math}")
"""
array([[53, 67, 62],
       [92, 82, 76],
       [72, 92, 98],
       [55, 56, 80],
       [68, 58, 67],
       [85, 73, 98],
       [67, 55, 69],
       [57, 87, 52],
       [96, 52, 85],
       [77, 67, 87]])
所有课程的均分:[72.2 68.9 77.4]
所有课程的最高分:[96 92 98], 最低分:[53 52 52]
每名学生的总分:
[182 250 262 191 193 256 191 196 233 231]
每门课程标准差:[14.44160656 13.49407277 14.38193311]
数学成绩的累积和:[ 53 145 217 272 340 425 492 549 645 722]
"""