4 ndarray运算

学习目标

  • 目标

    • 应用数组的通用判断函数

    • 应用np.where实现数组的三元运算


问题

如果想要操作符合某一条件的数据,应该怎么做?

1 逻辑运算

# 生成10名同学,5门功课的数据
>>> score = np.random.randint(40, 100, (10, 5))

# 取出最后4名同学的成绩,用于逻辑判断
>>> test_score = score[6:, 0:5]

# 逻辑判断, 如果成绩大于60就标记为True 否则为False
>>> test_score > 60
array([[ True,  True,  True, False,  True],
       [ True,  True,  True, False,  True],
       [ True,  True, False, False,  True],
       [False,  True,  True,  True,  True]])

# BOOL赋值, 将满足条件的设置为指定的值-布尔索引
>>> test_score[test_score > 60] = 1
>>> test_score
array([[ 1,  1,  1, 52,  1],
       [ 1,  1,  1, 59,  1],
       [ 1,  1, 44, 44,  1],
       [59,  1,  1,  1,  1]])

2 通用判断函数

  • np.all()

  • np.any()

3 np.where(三元运算符)

通过使用np.where能够进行更加复杂的运算

  • np.where()

  • 复合逻辑需要结合np.logical_and和np.logical_or使用

4 统计运算

如果想要知道学生成绩最大的分数,或者做小分数应该怎么做?

4.1 统计指标

在数据挖掘/机器学习领域,统计指标的值也是我们分析问题的一种方式。常用的指标如下:

  • min(a, axis)

    • Return the minimum of an array or minimum along an axis.

  • max(a, axis])

    • Return the maximum of an array or maximum along an axis.

  • median(a, axis)

    • Compute the median along the specified axis.

  • mean(a, axis, dtype)

    • Compute the arithmetic mean along the specified axis.

  • std(a, axis, dtype)

    • Compute the standard deviation along the specified axis.

  • var(a, axis, dtype)

    • Compute the variance along the specified axis.

4.2 案例:学生成绩统计运算

进行统计的时候,axis 轴的取值并不一定,Numpy中不同的API轴的值都不一样,在这里,axis 0代表列, axis 1代表行去进行统计

结果:

如果需要统计出某科最高分对应的是哪个同学?

  • np.argmax(temp, axis=)

  • np.argmin(temp, axis=)

结果:

Last updated