一、算数运算
a.加减乘除
import numpy as np
x = np.array([1, 2, 3, 4]).reshape([2, 2])
y = np.array([5.5, 6.5, 7.5, 8.5]).reshape([2, 2])
print('x = {}\n'.format(x))
print('y = {}\n'.format(y))
print('x + y = {}\n'.format(x + y))
print('add(x,y) = {}\n'.format(np.add(x, y)))
print('x - y = {}\n'.format(x - y))
print('subtract(x,y) = {}\n'.format(np.subtract(x, y)))
print('x * y = {}\n'.format(x * y))
print('multiply(x,y) = {}\n'.format(np.multiply(x, y)))
print('x / y = {}\n'.format(x / y))
print('divide(x,y) = {}\n'.format(np.divide(x, y)))
运行结果:
x = [[1 2]
[3 4]]
y = [[5.5 6.5]
[7.5 8.5]]
x + y = [[ 6.5 8.5]
[10.5 12.5]]
add(x,y) = [[ 6.5 8.5]
[10.5 12.5]]
x - y = [[-4.5 -4.5]
[-4.5 -4.5]]
subtract(x,y) = [[-4.5 -4.5]
[-4.5 -4.5]]
x * y = [[ 5.5 13. ]
[22.5 34. ]]
multiply(x,y) = [[ 5.5 13. ]
[22.5 34. ]]
x / y = [[0.18181818 0.30769231]
[0.4 0.47058824]]
divide(x,y) = [[0.18181818 0.30769231]
[0.4 0.47058824]]
b.统计学函数
import numpy as np
X = np.array([1, 2, 3, 4]).reshape([2, 2])
print()
print('X = \n', X)
print()
print('平均值:', X.mean())
print('列的平均值:', X.mean(axis=0))
print('行的平均值:', X.mean(axis=1))
print()
print('和:', X.sum())
print('列的和:', X.sum(axis=0))
print('行的和', X.sum(axis=1))
print()
print('标准差:', X.std())
print('列的标准差:', X.std(axis=0))
print('行的标准差:', X.std(axis=1))
print()
print('中值:', np.median(X))
print('列的中值:', np.median(X,axis=0))
print('行的中值:', np.median(X,axis=1))
print()
print('最大值:', X.max())
print('行的最大值:', X.max(axis=0))
print('列的最大值:', X.max(axis=1))
print()
print('最小值:', X.min())
print('列的最小值:', X.min(axis=0))
print('行的最小值:', X.min(axis=1))
运行结果:
X =
[[1 2]
[3 4]]
平均值: 2.5
列的平均值: [2. 3.]
行的平均值: [1.5 3.5]
和: 10
列的和: [4 6]
行的和 [3 7]
标准差: 1.118033988749895
列的标准差: [1. 1.]
行的标准差: [0.5 0.5]
中值: 2.5
列的中值: [2. 3.]
行的中值: [1.5 3.5]
最大值: 4
行的最大值: [3 4]
列的最大值: [2 4]
最小值: 1
列的最小值: [1 2]
行的最小值: [1 3]
二、广播
a.每个元素广播 * 3
X = np.array([1, 2, 3, 4]).reshape([2, 2])
print()
print('X = \n', X)
print()
#X中的每个元素 * 3
print('3 * X = \n', 3 * X)
运行结果:
X =
[[1 2]
[3 4]]
3 * X =
[[ 3 6]
[ 9 12]]
b.可以对俩个形状不同ndarray做广播,但是对形状有限制
import numpy as np
x = np.array([1, 2, 3])
Y = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Z = np.array([1, 2, 3]).reshape(3, 1)
print('x = \n', x)
print('Y = \n', Y)
print('Z = \n', Z)
print('x + Y = \n', x + Y)
print('Z + Y = \n', Z + Y)
运行结果:
x =
[1 2 3]
Y =
[[1 2 3]
[4 5 6]
[7 8 9]]
Z =
[[1]
[2]
[3]]
x + Y =
[[ 2 4 6]
[ 5 7 9]
[ 8 10 12]]
Z + Y =
[[ 2 3 4]
[ 6 7 8]
[10 11 12]]