在Numpy中进行数组运算或者数组操作时,返回结果为数组的副本或视图。 在Numpy中,所有赋值运算不会为数组和数组中的任何元素创建副本。
使用 numpy.ndarray.copy()函数来创建一个副本。对副本中的数据进行修改不会影响到原始数据,因为它们存放的物理地址不同。数组切片操作返回的是原数组的视图,而非副本数组索引机制指的是用方括号([])加序号的形式引用单个数组元素,它的用处很多,比如抽取元素,选取数组的几个元素,甚至为其赋一个新值。
类似于List的切片操作,然而对List的切片操作得到的是原数组的副本,而Numpy对数据进行切片操作得到的是指向相同缓冲区的视图。
切片语法: (start:stop:step)
为了更好地理解切片语法,还应该了解不明确指明起始和结束位置的情况。如省去第一个数字,numpy 会认为第一个数字是0;如省去第二个数字,numpy 则会认为第二个数字是数组的最大索引值;如省去最后一个数字,它将会被理解为1,也就是抽取所有元素而不再考虑间隔。
利用 :和负数进行切片
多位数组切片:通过逗号分隔不同维度,每个维度的切片操作是独立的
Numpy允许使用...来表示足够多的冒号来构建完整的索引列表 比如,如果 x 是 5 维数组:
x[1,2,...] 等于 x[1,2,:,:,:]x[...,3] 等于 x[:,:,:,:,3]x[4,...,5,:] 等于 x[4,:,:,5,:]方括号内可传入多个索引值,可以同时选择多个元素 可用于交换行、列的顺序或提取特定行、列构造新的数组
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 = np.array([[0, 0], [4, 4]]) c = np.array([[0, 4], [0, 4]]) y = x[r, c] print(y) # [[11 15] # [31 35]] # 获取了数组四个角的元素 切片也可以与整数数组相结合 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[0:3, [1, 2, 2]] print(y) # [[12 13 13] # [17 18 18] # [22 23 23]] numpy.take(a, indices, axis=None, out=None, mode='raise') Take elements from an array along an axis.注意:使用切片得到的视图始终为原数组的子数组;而整数索引得到的是新的数组可以通过一个布尔数组来索引目标数组 常用于筛选满足条件的数据
mport numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7, 8]) y = x > 5 print(y) # [False False False False False True True True] print(x[x > 5]) # [6 7 8] x = np.array([np.nan, 1, 2, np.nan, 3, 4, 5]) y = np.logical_not(np.isnan(x)) print(x[y]) # [1. 2. 3. 4. 5.] 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 > 25 print(y) # [[False False False False False] # [False False False False False] # [False False False False False] # [ True True True True True] # [ True True True True True]] print(x[x > 25]) # [26 27 28 29 30 31 32 33 34 35] numpy.logical_andx1, x2()numpy.logical_or(x1, x2)numpy.logical_not(x1, x2)numpy.logical_xor(x1, x2)为Numpy中的逻辑运算函数除了for循环,Numpy中还可以用apply_along_axis()进行数组的遍历 apply_along_axis(func1d, axis, arr)Apply a function to 1-D slices along the given axis.
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] y = np.apply_along_axis(np.mean, 0, x) print(y) # [21. 22. 23. 24. 25.] y = np.apply_along_axis(np.mean, 1, x) print(y) # [13. 18. 23. 28. 33.] 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.]axis=0为跨行(沿着行下标)的运算 axis=1为跨列(沿着列下标)的运算