【基本工具】S02E03 ndarray 基本运算方法解析

1.二维数组的转置与内积
2.数组的元素级别运算
3.条件逻辑运算where
4.各轴向上的统计运算
5.布尔数组的运算
6.数组的就地排序

# 1.二维数组的转置与内积

import numpy as np

arr = np.arange(15).reshape(5,3)
print(arr)
print(arr.T)  

[[ 0  1  2]
[ 3  4  5]
[ 6  7  8]
[ 9 10 11]
[12 13 14]]
[[ 0  3  6  9 12]
[ 1  4  7 10 13]
[ 2  5  8 11 14]]

import numpy as np

arr = np.arange(6).reshape(3,2)
print(arr)
print(arr.T)
print(np.dot(arr.T,arr))  

[[0 1]
[2 3]
[4 5]]

[[0 2 4]
[1 3 5]]

[[20 26]
[26 35]]

# 2.数组的元素级别运算

import numpy as np

arr1 = np.array([1,3,5,4,5])
arr2 = np.array([4,6,1,3,4])
print(np.sqrt(arr1))
print(np.square(arr2))
print(np.multiply(arr1,arr2))
print(np.subtract(arr1,arr2))  

[ 1.          1.73205081  2.23606798  2.          2.23606798]
[16 36  1  9 16]
[ 4 18  5 12 20]
[-3 -3  4  1  1]

# 3.条件逻辑的数组运算:np.where

import numpy as np

arr = np.random.randn(4,4)
print(arr)
print(np.where(arr>0,2,-2))
print(np.where(arr>0,2,arr))  

[[ 0.19699344 -0.6502777  -1.03611804 -0.43403437]
[-1.95661572  0.44830588 -0.98746604 -0.57244612]
[ 0.44935834 -0.67782579 -0.49945472 -0.46147115]
[-0.26284806 -0.4260144   0.43380332 -0.04461859]]

[[ 2 -2 -2 -2]
[-2  2 -2 -2]
[ 2 -2 -2 -2]
[-2 -2  2 -2]]

[[ 2.         -0.6502777  -1.03611804 -0.43403437]
[-1.95661572  2.         -0.98746604 -0.57244612]
[ 2.         -0.67782579 -0.49945472 -0.46147115]
[-0.26284806 -0.4260144   2.         -0.04461859]]

# 4.各轴向上的统计运算

import numpy as np

arr = np.array([[0,1,2],[3,4,5],[6,7,8]])
print(arr.mean())
print(arr.mean(axis=0))
print(arr.mean(axis=1))