注意:在 ndarray 中所有元素必须是同一类型,否则会自动向下转换, int->float->str
import numpy as np a = np.array([1, 2, 3, 4, 5]) print(a) # [1 2 3 4 5] b = np.array([1, 2, 3, 4, '5']) print(b) # ['1' '2' '3' '4' '5']#结果全为字符型 c = np.array([1, 2, 3, 4, 5.0]) print(c) # [1. 2. 3. 4. 5.]注意:numpy.ndarray.copy() 函数创建一个副本。 对副本数据进行修改,不会影响到原始数据,它们物理内存不在同一位置。
import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7, 8]) y = x y[0] = -1 print(x)# [-1 2 3 4 5 6 7 8] print(y)# [-1 2 3 4 5 6 7 8] x = np.array([1, 2, 3, 4, 5, 6, 7, 8]) y = x.copy() y[0] = -1 print(x)# [1 2 3 4 5 6 7 8] print(y)# [-1 2 3 4 5 6 7 8]数组切片操作返回的对象只是原数组的视图
import numpy as np x = np.array([[11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33, 34, 35]]) y = x y[::2, :3:2] = -1 print(x) #[[-1 12 -1 14 15] #[16 17 18 19 20] #[-1 22 -1 24 25] #[26 27 28 29 30] #[-1 32 -1 34 35]] print(y) #[[-1 12 -1 14 15] #[16 17 18 19 20] # [-1 22 -1 24 25] #[26 27 28 29 30] #[-1 32 -1 34 35]]注意:x[ , ]要比x[ ][ ]效率要高
x = np.array([[11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33, 34, 35]]) print(x[2]) # [21 22 23 24 25] print(x[2][1]) # 22 print(x[2, 1]) # 22对一位数组切片
import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7, 8]) print(x[0:2]) # [1 2] print(x[1:5:2]) # [2 4]对二维数组切片
import numpy as np x = np.array([[11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33, 34, 35]]) print(x[0:2]) # [[11 12 13 14 15] # [16 17 18 19 20]] print(x[::2, ::2]) # [[11 13 15] # [21 23 25] # [31 33 35]]注意:通过对每个以逗号分隔的维度执行单独的切片,可以对多维数组进行切片。因此,对于二维数组,第一块定义了行的切片,第二块定义了列的切片。
NumPy 允许使用 … 表示足够多的冒号来构建完整的索引列表。 比如,如果 x 是 5 维数组:
x[1,2,…] 等于 x[1,2,:,:,:]x[…,3] 等于 x[:,:,:,:,3]x[4,…,5,:] 等于 x[4,:,:,5,:]numpy.take(a,indices,axis = None,out = None,mode =‘raise’ ) 沿轴取数组中的元素 当axis不是None时,此函数与“fancy”索引(使用数组索引数组)的功能相同; 但是,如果您需要沿给定轴的元素,则可以更容易使用
import numpy as np x = np.array([[11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33, 34, 35]]) r = [0, 1, 2] print(np.take(x, r, axis=0)) # [[11 12 13 14 15] # [16 17 18 19 20] # [21 22 23 24 25]] r = [0, 1, 2] c = [2, 3, 4] y = np.take(x, [r, c]) print(y) # [[11 12 13] # [13 14 15]]apply_along_axis(func1d, axis, arr)
import numpy as np x = np.array([[11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33, 34, 35]]) y = np.apply_along_axis(np.sum, 0, x) print(y) # [105 110 115 120 125] y = np.apply_along_axis(np.sum, 1, x) print(y) # [ 65 90 115 140 165] def my_func(x): return (x[0] + x[-1]) * 0.5 y = np.apply_along_axis(my_func, 0, x) print(y) # [21. 22. 23. 24. 25.] y = np.apply_along_axis(my_func, 1, x) print(y) # [13. 18. 23. 28. 33.]