1 逻辑运算

  1. # 生成10名同学,5门功课的数据
  2. >>> score = np.random.randint(40, 100, (10, 5))
  3. # 取出最后4名同学的成绩,用于逻辑判断
  4. >>> test_score = score[6:, 0:5]
  5. # 逻辑判断, 如果成绩大于60就标记为True 否则为False
  6. >>> test_score > 60
  7. array([[ True, True, True, False, True],
  8. [ True, True, True, False, True],
  9. [ True, True, False, False, True],
  10. [False, True, True, True, True]])
  11. # BOOL赋值, 将满足条件的设置为指定的值-布尔索引
  12. >>> test_score[test_score > 60] = 1
  13. >>> test_score
  14. array([[ 1, 1, 1, 52, 1],
  15. [ 1, 1, 1, 59, 1],
  16. [ 1, 1, 44, 44, 1],
  17. [59, 1, 1, 1, 1]])

2 通用判断函数

  • np.all()

    1. # 判断前两名同学的成绩[0:2, :]是否全及格
    2. >>> np.all(score[0:2, :] > 60)
    3. False
  • np.any()

    1. # 判断前两名同学的成绩[0:2, :]是否有大于90分的
    2. >>> np.any(score[0:2, :] > 80)
    3. True

    3 np.where(三元运算符)

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

  • np.where()

    1. # 判断前四名学生,前四门课程中,成绩中大于60的置为1,否则为0
    2. temp = score[:4, :4]
    3. np.where(temp > 60, 1, 0)
  • 复合逻辑需要结合np.logical_and和np.logical_or使用 ```python

    判断前四名学生,前四门课程中,成绩中大于60且小于90的换为1,否则为0

    np.where(np.logical_and(temp > 60, temp < 90), 1, 0)

判断前四名学生,前四门课程中,成绩中大于90或小于60的换为1,否则为0

np.where(np.logical_or(temp > 90, temp < 60), 1, 0) ```

4 统计运算

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

4.1 统计指标

  • min(a, axis)
    • 求最小值
  • max(a, axis])
    • 求最大值
  • median(a, axis)
    • 求中位数
  • mean(a, axis, dtype)
    • 求平均值
  • std(a, axis, dtype)
    • 求均方差
  • var(a, axis, dtype)
    • 求方差