①add对应元素相加
②subtract对应元素相减
③数组元素相乘
④divide、floor_divide除法和向下取整(丢弃余数)
⑤power幂函数
⑥maximum、fmax返回两个数组较大者组成的数组
⑦mod取余
⑧greater、greater_equal、less、less_equal、equal、not_equal:元素比较运算相当于>、>=、<、<=、=、≠
⑨logical_and、logical_or、logical_xor元素真值运算相当于&、|、^
2.2.3常用函数库
1、
函数名 | 函数名 | ||
sum | 数组元素求和或对某轴向元素求和 | mean | 算术平均数 |
prod | 计算数组元素的乘积 | min | 计算各元素最小值 |
std | 标准差 | max | 计算各元素最大值 |
var | 方差 | argmin | 最小值元素索引 |
2、随机数
import numpy as np # 利用numpy.random产生随机数 print(np.random.rand(3, 2)) # 0~1均匀分布的样本 print(np.random.randn(3, 2)) # 正态分布的随机数,数组形状(3,2) print(np.random.normal(100, 10, (3, 2))) # 正态分布随机数,期望100,标准差10,数组形状(3,2) print(np.random.uniform(10, 30, (3, 2))) # 10~30的均匀分布 print(np.random.poisson()) # λ系数为5的泊松分布 print(np.random.permutation(5)) # [0,5]随机整数 a = [1, 2, 3] print(np.random.permutation(a)) # a的随机排列 print(np.random.randint(20, 50, 5)) # [20,50]范围内产生的5个随机数
输出结果如下
[[0.60905535 0.5787323 ]
[0.10360825 0.43054893]
[0.9497246 0.5508657 ]]
[[ 0.97825827 -0.34827194]
[ 1.12542917 0.40453609]
[-0.70208668 -0.17586244]]
[[ 85.51252714 91.30205883]
[101.39198047 95.19504388]
[ 85.07048564 111.45664473]]
[[21.971866 24.84019723]
[28.12806567 22.6673743 ]
[24.89224711 19.96258787]]
1
[1 0 3 2 4]
[2 1 3]
[42 42 29 34 28]
3、操作多维数组
import numpy as np # 操作多维数组 # ①沿0轴 a = np.array([1, 2, 3]) b = np.array([2, 3, 4]) c = np.vstack((a, b)) print('1st example of vstack:\n', c) d = np.array([[1], [2], [3]]) e = np.array([[2], [3], [4]]) f = np.vstack((d, e)) print('2nd example of vstack: \n', f)
1st example of vstack:
[[1 2 3]
[2 3 4]]
2nd example of vstack:
[[1]
[2]
[3]
[2]
[3]
[4]]
# ②沿1轴 g = np.hstack((a, b)) print('1st example of hstack:\n', g) h = np.hstack((d, e)) print('2nd example of hstack:\n', h)
1st example of hstack:
[1 2 3 2 3 4]
2nd example of hstack:
[[1 2]
[2 3]
[3 4]]
[[ 7 21 3 14 16 3 12 16 0 20 16 22]
[15 6 18 6 13 1 1 24 12 12 5 7]]
# ③沿水平轴分拆 i = np.random.randint(0, 25, (2, 12)) j = np.hsplit(i, 3) print(i) print(j)
[array([[ 7, 21, 3, 14],
[15, 6, 18, 6]]), array([[16, 3, 12, 16],
[13, 1, 1, 24]]), array([[ 0, 20, 16, 22],
[12, 12, 5, 7]])]