索引
数组索引机制指的是用方括号([])加序号的形式引用单个数组元素,它的用处很多,比如抽取元素,选取数组的几个元素,甚至为其赋一个新值。
1.1整数索引
要获取数组的单个元素,指定元素的索引即可。
一维数组
import numpy as np
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
print(x[2]) # 3
二维数组
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
1.2切片索引
切片操作是指抽取数组的一部分元素生成新数组。
对一维数组的切片
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]
print(x[2:]) # [3 4 5 6 7 8]
print(x[:2]) # [1 2]
print(x[-2:]) # [7 8]
print(x[:-2]) # [1 2 3 4 5 6]
print(x[:]) # [1 2 3 4 5 6 7 8]
print(x[::-1]) # [8 7 6 5 4 3 2 1]
二维数组的切片和一维数组的切片类似,就是多了一维,要从x[:]变成x[:, :])。
1.3 dots索引
NumPy 允许使用 … 表示足够多的冒号来构建完整的索引列表。
x[1,2,…] 等于 x[1,2,:,:,:]
x[…,3] 等于 x[:,:,:,:,3]
x[4,…,5,:] 等于 x[4,:,:,5,:]
1.4整数数组索引
方括号内传入多个索引值,可以同时选择多个元素。
import numpy as np
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
r = [0, 1, 2]
print(x[r])
# [1 2 3]
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] #行索引
c = [2, 3, 4] #列索引
y = x[r, c]
print(y)
# [13 19 25]
可以通过对 r 创建数组,来提取索引
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, 1], [3, 4]]) #行索引
print(x[r])
# [[[11 12 13 14 15]
[16 17 18 19 20]]
#
# [[26 27 28 29 30]
[31 32 33 34 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]])
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]]
若要沿纵轴获取元素,axis=1
可以在上述代码中尝试加入行、列索引,操作和前一代码块类似。
1.5布尔索引
通过一个布尔数组来索引目标数组。
二维数组同下操作。
import 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.]
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 50) #给x赋值
y = np.sin(x) #计算sin(x)值
print(len(x)) # 50
plt.plot(x, y)
mask = y >= 0 #y值大于等于0
print(len(x[mask])) # 25
print(mask)#输出mask的值,大于等于0的为true,其他为False
在这里可以设定条件,赋值给mask,例如可以改为:
mask = np.logical_and(y >= 0, x <= np.pi / 2)
再输出mask。
1.6 数组的迭代
除了for循环,Numpy 还提供另外一种更为优雅的遍历方法。
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.]