「numpy」ndarray 逻辑运算,通用判断,三元运算,统计量计算

0 阅读2分钟

numpy ndarray 运算

【目录】

  • 逻辑运算
  • 通用判断函数
  • 三元运算符 np.where()
  • 统计计算

一、逻辑运算

  • 所有逻辑运算符,比如:>, <, >=, ==
 x = np.random.randint(0, 100, (2, 3))
 print(x)
 print(x > 50)
 x[x < 30] = 1
 print(x)
 ​
 # 返回结果
 [[69 62 23]
  [21 89 25]]
 ​
 [[ True  True False]
  [False  True False]]
 ​
 [[69 62  1]
  [ 1 89  1]]

二、通用判断函数

  • np.all(exp) 全部满足才行
  • np.any(exp) 有一个满足就行
 x = np.array([[69, 62, 23], [21, 89, 25]])
 ​
 np.all(x > 60)  # False
 ​
 np.any(x > 80)  # True

三、三元运算符

  • np.where(exp),返回一个结果对象

    • 与C/C++中的三元运算符语法、功能一致
 x = np.array([[69, 62, 23], [21, 89, 25]])
 ​
 y = np.where(x > 60, 1, 0)  # 大于60的赋值为1,否则为0
 ​
 print(y)
 ​
 # 返回结果
 [[1 1 0]
  [0 1 0]]

  • np.logical_and 和 np.local_or

    • 复合型逻辑运算
 x = np.array([[69, 62, 23], [21, 89, 25]])
 ​
 y1 = np.where(np.logical_and(x > 60, x < 90), 1, 0)
 ​
 y2 = np.where(np.logical_or(x > 90, x < 60), 1, 0)
 ​
 print(y1)
 # 返回结果
 [[1 1 0]
  [0 1 0]]
 ​
 print(y2)
 # 返回结果
 [[0 0 1]
  [1 0 1]]

四、统计计算

  • min(a, axis)

    • 计算最小值,axis表示指定行或者列,默认不指定
  • max(a, axis])

    • 计算最大值,axis表示指定行或者列,默认不指定
  • median(a, axis)

    • 计算中位数,axis表示指定行或者列,默认不指定
  • mean(a, axis, dtype)

    • 计算平均值,axis表示指定行或者列,默认不指定
  • std(a, axis, dtype)

    • 计算标准差,axis表示指定行或者列,默认不指定
  • var(a, axis, dtype)

    • 计算方差,axis表示指定行或者列,默认不指定
 x = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
 ​
 print(f"数组中的最小值:{np.min(x)}")
 print(f"数组中的最大值:{np.max(x)}")
 print(f"数组中的中位数:{np.median(x)}")
 print(f"数组中的平均值:{np.mean(x)}")
 print(f"数组中的标准差:{np.std(x):.2f}")
 print(f"数组中的方差:{np.var(x)}")
 ​
 # 返回结果
 数组中的最小值:1
 数组中的最大值:10
 数组中的中位数:5.5
 数组中的平均值:5.5
 数组中的标准差:2.87
 数组中的方差:8.25

  • np.argmax(a, axis=)

  • np.argmin(a, axis=)

    • 两个函数表示的是最大值和最小值对应的数组下标
 x = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
 ​
 print(f"数组最大值对应的下标:{np.argmax(x)}")
 print(f"数组最小值对应的下标:{np.argmin(x)}")
 ​
 # 返回结果
 数组最大值对应的下标:9
 数组最小值对应的下标:0