一些更高级的ndarray处理
where和一些其他的逻辑运算
np.where(cond,x,y):满足条件(cond)输出x,不满足输出y
x_arr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])y_arr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])cond = np.array([True, False, True, True, False])print(np.where(cond, x_arr, y_arr))
[ 1.1 2.2 1.3 1.4 2.5]
arr = np.random.randn(4,4)print(arr)print(np.where(arr > 0, 2, -2))print(np.where(arr > 0, 2, arr))
[[ -1.10484247e+00 -3.82422727e-01 -3.24361549e-01 1.21286234e+00] [ 1.54499855e-01 -4.77728163e-04 1.44621074e+00 -2.64241611e-03] [ 1.36394862e+00 6.96638259e-02 -2.75237740e-01 -3.32892881e-01] [ -1.37165175e+00 1.79997993e-01 -1.13509664e-01 1.88373639e+00]][[-2 -2 -2 2] [ 2 -2 2 -2] [ 2 2 -2 -2] [-2 2 -2 2]][[ -1.10484247e+00 -3.82422727e-01 -3.24361549e-01 2.00000000e+00] [ 2.00000000e+00 -4.77728163e-04 2.00000000e+00 -2.64241611e-03] [ 2.00000000e+00 2.00000000e+00 -2.75237740e-01 -3.32892881e-01] [ -1.37165175e+00 2.00000000e+00 -1.13509664e-01 2.00000000e+00]]
np.where可以嵌套使用
cond_1 = np.array([True, False, True, True, False])cond_2 = np.array([False, True, False, True, False])result = np.where(cond_1 & cond_2, 0, np.where(cond_1, 1, np.where(cond_2, 2, 3)))print(result)
[1 2 1 0 3]
arr = np.random.randn(10)print(arr)print((arr > 0).sum()) #数组中大于0的数相加
[ 0.27350655 -1.51093462 0.26835915 -0.45991855 1.34450904 -1.86871203 0.04308971 1.69640444 -0.02191351 -0.43875275]5
bools = np.array([False, False, True, False])print(bools.any()) # 有一个为True则返回Trueprint(bools.all()) # 有一个为False则返回False
TrueFalse
reshape(数组变形)
numpy可以很容易地把一维数组转成二维数组,三维数组。
import numpy as nparr = np.arange(8)print("(4,2):", arr.reshape((4,2)))print()print("(2,2,2):", arr.reshape((2,2,2)))
(4,2): [[0 1] [2 3] [4 5] [6 7]](2,2,2): [[[0 1] [2 3]] [[4 5] [6 7]]]
-1( 维度自动推算)
如果我们在某一个维度上写上-1,numpy会帮我们自动推导出正确的维度
arr = np.arange(15)print(arr.reshape((5,-1)))print(arr.reshape((5,-1)).shape)
[[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11] [12 13 14]](5, 3)
ravel(拉平数组)
# 高维数组用ravel来拉平成为一维数组arr = np.arange(15)print(arr.ravel())
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
concatenate(连接数组)
arr1 = np.array([[1, 2, 3], [4, 5, 6]])arr2 = np.array([[7, 8, 9], [10, 11, 12]])print(np.concatenate([arr1