-
- 布尔数组索引:使用一个布尔数组作为索引,可以根据布尔数组的元素值来选择数组中的元素。
import numpy as np
a = np.array([1, 2, 3, 4, 5])
# 使用布尔数组索引选择大于3的元素
mask = a > 3
result = a[mask]
print(result)
输出:
[4, 5]
还可以按布尔数组进行匹配
arr = np.array([1, 2, 3, 4, 5])
mask = np.array([True, False, True, False, True]) # 选择为True的元素
print(arr[mask]) # 输出 [1 3 5]
-
- 花式索引(Fancy indexing):使用整数数组或整数列表作为索引,可以根据指定的索引位置选择数组中的元素。
import numpy as np
a = np.array([1, 2, 3, 4, 5])
# 使用花式索引获取指定位置的元素
indices = np.array([0, 2, 4])
result = a[indices]
print(result)
输出:
array([1, 3, 5])
多维数组的操作与此类似,如果有时间,不妨在上述例子上动手试一下,记住,如果使用负整数,索引会从末尾倒着开始哦。
4.3 数组操作
NumPy提供了一些方便的函数来操作数组,包括连接数组、分割数组、改变数组形状和交换数组维度等。
-
- 连接数组:使用
np.concatenate()
函数沿指定轴连接数组
- 连接数组:使用
import numpy as np
a = np.array([[1, 2],
[3, 4]])
b = np.array([[5, 6],
[7, 8]])
# 沿行方向连接数组
result = np.concatenate((a, b), axis=0)
print(result)
输出:
[[1, 2]
[3, 4]
[5, 6]
[7, 8]]
-
- 分割数组:使用
np.split()
函数将数组分割为多个子数组
- 分割数组:使用
import numpy as np
a = np.array([1, 2, 3, 4, 5])
# 将数组分割为3个子数组
result = np.array_split(a, 3)
print(result)
输出: