46使用 Python 中的值创建 3D NumPy 数组
import numpy as np the_3d_array = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) print(the_3d_array)
Output:
[[[1 2] [3 4]] [[5 6] [7 8]]]
47计算不同长度的 Numpy 数组的平均值
import numpy as np x = np.array([[1, 2], [3, 4]]) y = np.array([[1, 2, 3], [3, 4, 5]]) z = np.array([[7], [8]]) arr = np.ma.empty((2, 3, 3)) arr.mask = True arr[:x.shape[0], :x.shape[1], 0] = x arr[:y.shape[0], :y.shape[1], 1] = y arr[:z.shape[0], :z.shape[1], 2] = z print(arr.mean(axis=2))
Output:
[[3.0 2.0 3.0] [4.666666666666667 4.0 5.0]]
48从 Numpy 数组中删除 nan 值
Example 1
import numpy as np x = np.array([np.nan, 2, 3, 4]) x = x[~np.isnan(x)] print(x)
Output:
[2. 3. 4.]
Example 2
import numpy as np x = np.array([ [5, np.nan], [np.nan, 0], [1, 2], [3, 4] ]) x = x[~np.isnan(x).any(axis=1)] print(x)
Output:
[[1. 2.] [3. 4.]]
49向 NumPy 数组添加一列
import numpy as np the_array = np.array([[1, 2], [3, 4]]) columns_to_append = np.array([[5], [6]]) the_array = np.append(the_array, columns_to_append, 1) print(the_array)
Output:
[[1 2 5] [3 4 6]]
50在 Numpy Array 中打印浮点值时如何抑制科学记数法
import numpy as np np.set_printoptions(suppress=True, formatter={'float_kind': '{:f}'.format}) the_array = np.array([3.74, 5162, 13683628846.64, 12783387559.86, 1.81]) print(the_array)
Output:
[3.740000 5162.000000 13683628846.639999 12783387559.860001 1.810000]
51Numpy 将 1d 数组重塑为 1 列的 2d 数组
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8]) newarr = arr.reshape(arr.shape[0], -1) print(newarr)
Output:
[[1] [2] [3] [4] [5] [6] [7] [8]]
52初始化 NumPy 数组
import numpy as np thearray = np.array([[1, 2], [3, 4], [5, 6]]) print(thearray)
Output:
[[1 2] [3 4] [5 6]]
53创建重复一行
import numpy as np the_array = np.array([1, 2, 3]) repeat = 3 new_array = np.tile(the_array, (repeat, 1)) print(new_array)
Output:
[[1 2 3] [1 2 3] [1 2 3]]
54将 NumPy 数组附加到 Python 中的空数组
import numpy as np the_array = np.array([1, 2, 3, 4]) empty_array = np.array([]) new_array = np.append(empty_array, the_array) print(new_array)
Output:
[1. 2. 3. 4.]
55找到 Numpy 数组的平均值
计算每列的平均值
import numpy as np the_array = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) mean_array = the_array.mean(axis=0) print(mean_array)
Output:
[3. 4. 5. 6.]
计算每一行的平均值
import numpy as np the_array = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) mean_array = the_array.mean(axis=1) print(mean_array)
Output:
[2.5 6.5]
仅第一列的平均值
import numpy as np the_array = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) mean_array = the_array[:, 0].mean() print(mean_array)
Output:
3.0
仅第二列的平均值
import numpy as np the_array = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) mean_array = the_array[:, 0].mean() print(mean_array)
Output:
4.0
56检测 NumPy 数组是否包含至少一个非数字值
import numpy as np the_array = np.array([np.nan, 2, 3, 4]) array_has_nan = np.isnan(the_array).any() print(array_has_nan) the_array = np.array([1, 2, 3, 4]) array_has_nan = np.isnan(the_array).any() print(array_has_nan)
Output:
True False
57在 Python 中附加 NumPy 数组
import numpy as np the_array = np.array([[0, 1], [2, 3]]) row_to_append = np.array([[4, 5]]) the_array = np.append(the_array, row_to_append, 0) print(the_array) print('*' * 10) columns_to_append = np.array([[7], [8], [9]]) the_array = np.append(the_array, columns_to_append, 1) print(the_array)
Output:
[[0 1] [2 3] [4 5]] ********** [[0 1 7] [2 3 8] [4 5 9]]
58使用 numpy.any()
import numpy as np thearr = [[True, False], [True, True]] thebool = np.any(thearr) print(thebool) thearr = [[False, False], [False, False]] thebool = np.any(thearr) print(thebool)
Output:
True False
59获得 NumPy 数组的转置
import numpy as np the_array = np.array([[1, 2], [3, 4]]) print(the_array) print(the_array.T)
Output:
[[1 2] [3 4]] [[1 3] [2 4]]
60获取和设置NumPy数组的数据类型
import numpy as np type1 = np.array([1, 2, 3, 4, 5, 6]) type2 = np.array([1.5, 2.5, 0.5, 6]) type3 = np.array(['a', 'b', 'c']) type4 = np.array(["Canada", "Australia"], dtype='U5') type5 = np.array([555, 666], dtype=float) print(type1.dtype) print(type2.dtype) print(type3.dtype) print(type4.dtype) print(type5.dtype) print(type4)
Output:
int32 float64 <U1 <U5 float64 ['Canad' 'Austr']
61获得NumPy数组的形状
import numpy as np array1d = np.array([1, 2, 3, 4, 5, 6]) array2d = np.array([[1, 2, 3], [4, 5, 6]]) array3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) print(array1d.shape) print(array2d.shape) print(array3d.shape)
Output:
(6,) (2, 3) (2, 2, 3)
62获得 1、2 或 3 维 NumPy 数组
import numpy as np array1d = np.array([1, 2, 3, 4, 5, 6]) print(array1d.ndim) # 1 array2d = np.array([[1, 2, 3], [4, 5, 6]]) print(array2d.ndim) # 2 array3d = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) array3d = array3d.reshape(2, 3, 2) print(array3d.ndim) # 3
Output:
1 2 3
63重塑 NumPy 数组
import numpy as np thearray = np.array([1, 2, 3, 4, 5, 6, 7, 8]) thearray = thearray.reshape(2, 4) print(thearray) print("-" * 10) thearray = thearray.reshape(4, 2) print(thearray) print("-" * 10) thearray = thearray.reshape(8, 1) print(thearray)
Output:
[[1 2 3 4] [5 6 7 8]] ---------- [[1 2] [3 4] [5 6] [7 8]] ---------- [[1] [2] [3] [4] [5] [6] [7] [8]]
64调整 NumPy 数组的大小
import numpy as np thearray = np.array([1, 2, 3, 4, 5, 6, 7, 8]) thearray.resize(4) print(thearray) print("-" * 10) thearray = np.array([1, 2, 3, 4, 5, 6, 7, 8]) thearray.resize(2, 4) print(thearray) print("-" * 10) thearray = np.array([1, 2, 3, 4, 5, 6, 7, 8]) thearray.resize(3, 3) print(thearray)
Output:
[1 2 3 4] ---------- [[1 2 3 4] [5 6 7 8]] ---------- [[1 2 3] [4 5 6] [7 8 0]]
65将 List 或 Tuple 转换为 NumPy 数组
import numpy as np thelist = [1, 2, 3] print(type(thelist)) # <class 'list'> array1 = np.array(thelist) print(type(array1)) # <class 'numpy.ndarray'> thetuple = ((1, 2, 3)) print(type(thetuple)) # <class 'tuple'> array2 = np.array(thetuple) print(type(array2)) # <class 'numpy.ndarray'> array3 = np.array([thetuple, thelist, array1]) print(array3)
Output:
<class 'list'> <class 'numpy.ndarray'> <class 'tuple'> <class 'numpy.ndarray'> [[1 2 3] [1 2 3] [1 2 3]]
66使用 arange 函数创建 NumPy 数组
import numpy as np array1d = np.arange(5) # 1 row and 5 columns print(array1d) array1d = np.arange(0, 12, 2) # 1 row and 6 columns print(array1d) array2d = np.arange(0, 12, 2).reshape(2, 3) # 2 rows 3 columns print(array2d) array3d = np.arange(9).reshape(3, 3) # 3 rows and columns print(array3d)
Output:
[0 1 2 3 4] [ 0 2 4 6 8 10] [[ 0 2 4] [ 6 8 10]] [[0 1 2] [3 4 5] [6 7 8]]
67使用 linspace() 创建 NumPy 数组
import numpy as np array1d = np.linspace(1, 12, 2) print(array1d) array1d = np.linspace(1, 12, 4) print(array1d) array2d = np.linspace(1, 12, 12).reshape(4, 3) print(array2d)
Output:
[ 1. 12.] [ 1. 4.66666667 8.33333333 12. ] [[ 1. 2. 3.] [ 4. 5. 6.] [ 7. 8. 9.] [10. 11. 12.]]
68NumPy 日志空间数组示例
import numpy as np thearray = np.logspace(5, 10, num=10, base=10000000.0, dtype=float) print(thearray)
Output:
[1.00000000e+35 7.74263683e+38 5.99484250e+42 4.64158883e+46 3.59381366e+50 2.78255940e+54 2.15443469e+58 1.66810054e+62 1.29154967e+66 1.00000000e+70]
69创建 Zeros NumPy 数组
import numpy as np array1d = np.zeros(3) print(array1d) array2d = np.zeros((2, 4)) print(array2d)
Output:
[0. 0. 0.] [[0. 0. 0. 0.] [0. 0. 0. 0.]]
70NumPy One 数组示例
import numpy as np array1d = np.ones(3) print(array1d) array2d = np.ones((2, 4)) print(array2d)
Output:
[1. 1. 1.] [[1. 1. 1. 1.] [1. 1. 1. 1.]]
71NumPy 完整数组示例
import numpy as np array1d = np.full((3), 2) print(array1d) array2d = np.full((2, 4), 3) print(array2d)
Output:
[2 2 2] [[3 3 3 3] [3 3 3 3]]
72NumPy Eye 数组示例
import numpy as np array1 = np.eye(3, dtype=int) print(array1) array2 = np.eye(5, k=2) print(array2)
Output:
[[1 0 0] [0 1 0] [0 0 1]] [[0. 0. 1. 0. 0.] [0. 0. 0. 1. 0.] [0. 0. 0. 0. 1.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.]]
73NumPy 生成随机数数组
import numpy as np print(np.random.rand(3, 2)) # Uniformly distributed values. print(np.random.randn(3, 2)) # Normally distributed values. # Uniformly distributed integers in a given range. print(np.random.randint(2, size=10)) print(np.random.randint(5, size=(2, 4)))
Output:
[[0.68428242 0.62467648] [0.28595395 0.96066372] [0.63394485 0.94036659]] [[0.29458704 0.84015551] [0.42001253 0.89660667] [0.50442113 0.46681958]] [0 1 1 0 0 0 0 1 0 0] [[3 3 2 3] [2 1 2 0]]
74NumPy 标识和对角线数组示例
import numpy as np print(np.identity(3)) print(np.diag(np.arange(0, 8, 2))) print(np.diag(np.diag(np.arange(9).reshape((3,3)))))
Output:
[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]] [[0 0 0 0] [0 2 0 0] [0 0 4 0] [0 0 0 6]] [[0 0 0] [0 4 0] [0 0 8]]
75NumPy 索引示例
import numpy as np array1d = np.array([1, 2, 3, 4, 5, 6]) print(array1d[0]) # Get first value print(array1d[-1]) # Get last value print(array1d[3]) # Get 4th value from first print(array1d[-5]) # Get 5th value from last # Get multiple values print(array1d[[0, -1]]) print("-" * 10) array2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(array2d) print("-" * 10) print(array2d[0, 0]) # Get first row first col print(array2d[0, 1]) # Get first row second col print(array2d[0, 2]) # Get first row third col print(array2d[0, 1]) # Get first row second col print(array2d[1, 1]) # Get second row second col print(array2d[2, 1]) # Get third row second col
Output:
1 6 4 2 [1 6] ---------- [[1 2 3] [4 5 6] [7 8 9]] ---------- 1 2 3 2 5 8
76多维数组中的 NumPy 索引
import numpy as np array3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) print(array3d) print(array3d[0, 0, 0]) print(array3d[0, 0, 1]) print(array3d[0, 0, 2]) print(array3d[0, 1, 0]) print(array3d[0, 1, 1]) print(array3d[0, 1, 2]) print(array3d[1, 0, 0]) print(array3d[1, 0, 1]) print(array3d[1, 0, 2]) print(array3d[1, 1, 0]) print(array3d[1, 1, 1]) print(array3d[1, 1, 2])
Output:
[[[ 1 2 3] [ 4 5 6]] [[ 7 8 9] [10 11 12]]] 1 2 3 4 5 6 7 8 9 10 11 12
77NumPy 单维切片示例
import numpy as np array1d = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) print(array1d[4:]) # From index 4 to last index print(array1d[:4]) # From index 0 to 4 index print(array1d[4:7]) # From index 4(included) up to index 7(excluded) print(array1d[:-1]) # Excluded last element print(array1d[:-2]) # Up to second last index(negative index) print(array1d[::-1]) # From last to first in reverse order(negative step) print(array1d[::-2]) # All odd numbers in reversed order print(array1d[-2::-2]) # All even numbers in reversed order print(array1d[::]) # All elements
Output:
[4 5 6 7 8 9] [0 1 2 3] [4 5 6] [0 1 2 3 4 5 6 7 8] [0 1 2 3 4 5 6 7] [9 8 7 6 5 4 3 2 1 0] [9 7 5 3 1] [8 6 4 2 0] [0 1 2 3 4 5 6 7 8 9]
78NumPy 数组中的多维切片
import numpy as np array2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print("-" * 10) print(array2d[:, 0:2]) # 2nd and 3rd col print("-" * 10) print(array2d[1:3, 0:3]) # 2nd and 3rd row print("-" * 10) print(array2d[-1::-1, -1::-1]) # Reverse an array
Output:
---------- [[1 2] [4 5] [7 8]] ---------- [[4 5 6] [7 8 9]] ---------- [[9 8 7] [6 5 4] [3 2 1]]
79翻转 NumPy 数组的轴顺序
import numpy as np array2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(array2d) print("-" * 10) # Permute the dimensions of an array. arrayT = np.transpose(array2d) print(arrayT) print("-" * 10) # Flip array in the left/right direction. arrayFlr = np.fliplr(array2d) print(arrayFlr) print("-" * 10) # Flip array in the up/down direction. arrayFud = np.flipud(array2d) print(arrayFud) print("-" * 10) # Rotate an array by 90 degrees in the plane specified by axes. arrayRot90 = np.rot90(array2d) print(arrayRot90)
Output:
[[1 2 3] [4 5 6] [7 8 9]] ---------- [[1 4 7] [2 5 8] [3 6 9]] ---------- [[3 2 1] [6 5 4] [9 8 7]] ---------- [[7 8 9] [4 5 6] [1 2 3]] ---------- [[3 6 9] [2 5 8] [1 4 7]]
80NumPy 数组的连接和堆叠
import numpy as np array1 = np.array([[1, 2, 3], [4, 5, 6]]) array2 = np.array([[7, 8, 9], [10, 11, 12]]) # Stack arrays in sequence horizontally (column wise). arrayH = np.hstack((array1, array2)) print(arrayH) print("-" * 10) # Stack arrays in sequence vertically (row wise). arrayV = np.vstack((array1, array2)) print(arrayV) print("-" * 10) # Stack arrays in sequence depth wise (along third axis). arrayD = np.dstack((array1, array2)) print(arrayD) print("-" * 10) # Appending arrays after each other, along a given axis. arrayC = np.concatenate((array1, array2)) print(arrayC) print("-" * 10) # Append values to the end of an array. arrayA = np.append(array1, array2, axis=0) print(arrayA) print("-" * 10) arrayA = np.append(array1, array2, axis=1) print(arrayA)
Output:
[[ 1 2 3 7 8 9] [ 4 5 6 10 11 12]] ---------- [[ 1 2 3] [ 4 5 6] [ 7 8 9] [10 11 12]] ---------- [[[ 1 7] [ 2 8] [ 3 9]] [[ 4 10] [ 5 11] [ 6 12]]] ---------- [[ 1 2 3] [ 4 5 6] [ 7 8 9] [10 11 12]] ---------- [[ 1 2 3] [ 4 5 6] [ 7 8 9] [10 11 12]] ---------- [[ 1 2 3 7 8 9] [ 4 5 6 10 11 12]]
81NumPy 数组的算术运算
import numpy as np array1 = np.array([[1, 2, 3], [4, 5, 6]]) array2 = np.array([[7, 8, 9], [10, 11, 12]]) print(array1 + array2) print("-" * 20) print(array1 - array2) print("-" * 20) print(array1 * array2) print("-" * 20) print(array2 / array1) print("-" * 40) print(array1 ** array2) print("-" * 40)
Output:
[[ 8 10 12] [14 16 18]] -------------------- [[-6 -6 -6] [-6 -6 -6]] -------------------- [[ 7 16 27] [40 55 72]] -------------------- [[7. 4. 3. ] [2.5 2.2 2. ]] ---------------------------------------- [[ 1 256 19683] [ 1048576 48828125 -2118184960]] ----------------------------------------
82NumPy 数组上的标量算术运算
import numpy as np array1 = np.array([[10, 20, 30], [40, 50, 60]]) print(array1 + 2) print("-" * 20) print(array1 - 5) print("-" * 20) print(array1 * 2) print("-" * 20) print(array1 / 5) print("-" * 20) print(array1 ** 2) print("-" * 20)
Output:
[[12 22 32] [42 52 62]] -------------------- [[ 5 15 25] [35 45 55]] -------------------- [[ 20 40 60] [ 80 100 120]] -------------------- [[ 2. 4. 6.] [ 8. 10. 12.]] -------------------- [[ 100 400 900] [1600 2500 3600]] --------------------
83NumPy 初等数学函数
import numpy as np array1 = np.array([[10, 20, 30], [40, 50, 60]]) print(np.sin(array1)) print("-" * 40) print(np.cos(array1)) print("-" * 40) print(np.tan(array1)) print("-" * 40) print(np.sqrt(array1)) print("-" * 40) print(np.exp(array1)) print("-" * 40) print(np.log10(array1)) print("-" * 40)
Output:
[[-0.54402111 0.91294525 -0.98803162] [ 0.74511316 -0.26237485 -0.30481062]] ---------------------------------------- [[-0.83907153 0.40808206 0.15425145] [-0.66693806 0.96496603 -0.95241298]] ---------------------------------------- [[ 0.64836083 2.23716094 -6.4053312 ] [-1.11721493 -0.27190061 0.32004039]] ---------------------------------------- [[3.16227766 4.47213595 5.47722558] [6.32455532 7.07106781 7.74596669]] ---------------------------------------- [[2.20264658e+04 4.85165195e+08 1.06864746e+13] [2.35385267e+17 5.18470553e+21 1.14200739e+26]] ---------------------------------------- [[1. 1.30103 1.47712125] [1.60205999 1.69897 1.77815125]] ----------------------------------------
84NumPy Element Wise 数学运算
import numpy as np array1 = np.array([[10, 20, 30], [40, 50, 60]]) array2 = np.array([[2, 3, 4], [4, 6, 8]]) array3 = np.array([[-2, 3.5, -4], [4.05, -6, 8]]) print(np.add(array1, array2)) print("-" * 40) print(np.power(array1, array2)) print("-" * 40) print(np.remainder((array2), 5)) print("-" * 40) print(np.reciprocal(array3)) print("-" * 40) print(np.sign(array3)) print("-" * 40) print(np.ceil(array3)) print("-" * 40) print(np.round(array3)) print("-" * 40)
Output:
[[12 23 34] [44 56 68]] ---------------------------------------- [[ 100 8000 810000] [ 2560000 -1554869184 -1686044672]] ---------------------------------------- [[2 3 4] [4 1 3]] ---------------------------------------- [[-0.5 0.28571429 -0.25 ] [ 0.24691358 -0.16666667 0.125 ]] ---------------------------------------- [[-1. 1. -1.] [ 1. -1. 1.]] ---------------------------------------- [[-2. 4. -4.] [ 5. -6. 8.]] ---------------------------------------- [[-2. 4. -4.] [ 4. -6. 8.]] ----------------------------------------
85NumPy 聚合和统计函数
import numpy as np array1 = np.array([[10, 20, 30], [40, 50, 60]]) print("Mean: ", np.mean(array1)) print("Std: ", np.std(array1)) print("Var: ", np.var(array1)) print("Sum: ", np.sum(array1)) print("Prod: ", np.prod(array1))
Output:
Mean: 35.0 Std: 17.07825127659933 Var: 291.6666666666667 Sum: 210 Prod: 720000000
86Where 函数的 NumPy 示例
import numpy as np before = np.array([[1, 2, 3], [4, 5, 6]]) # If element is less than 4, mul by 2 else by 3 after = np.where(before < 4, before * 2, before * 3) print(after)
Output:
[[ 2 4 6] [12 15 18]]
87Select 函数的 NumPy 示例
import numpy as np before = np.array([[1, 2, 3], [4, 5, 6]]) # If element is less than 4, mul by 2 else by 3 after = np.select([before < 4, before], [before * 2, before * 3]) print(after)
Output:
[[ 2 4 6] [12 15 18]]
88选择函数的 NumPy 示例
import numpy as np before = np.array([[0, 1, 2], [2, 0, 1], [1, 2, 0]]) choices = [5, 10, 15] after = np.choose(before, choices) print(after) print("-" * 10) before = np.array([[0, 0, 0], [2, 2, 2], [1, 1, 1]]) choice1 = [5, 10, 15] choice2 = [8, 16, 24] choice3 = [9, 18, 27] after = np.choose(before, (choice1, choice2, choice3)) print(after)
Output:
[[ 5 10 15] [15 5 10] [10 15 5]] ---------- [[ 5 10 15] [ 9 18 27] [ 8 16 24]]
89NumPy 逻辑操作,用于根据给定条件从数组中选择性地选取值
import numpy as np thearray = np.array([[10, 20, 30], [14, 24, 36]]) print(np.logical_or(thearray < 10, thearray > 15)) print("-" * 30) print(np.logical_and(thearray < 10, thearray > 15)) print("-" * 30) print(np.logical_not(thearray < 20)) print("-" * 30)
Output:
[[False True True] [False True True]] ------------------------------ [[False False False] [False False False]] ------------------------------ [[False True True] [False True True]] ------------------------------
90标准集合操作的 NumPy 示例
import numpy as np array1 = np.array([[10, 20, 30], [14, 24, 36]]) array2 = np.array([[20, 40, 50], [24, 34, 46]]) # Find the union of two arrays. print(np.union1d(array1, array2)) # Find the intersection of two arrays. print(np.intersect1d(array1, array2)) # Find the set difference of two arrays. print(np.setdiff1d(array1, array2))
Output:
[10 14 20 24 30 34 36 40 46 50] [20 24] [10 14 30 36]