07 numpy 算數運算和廣播

一、算數運算

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]]

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章