有范围索引(Fancy Indexing):
无范围索引(Basic Indexing):
有范围索引的优势:
无范围索引的优势:
有范围索引的应用场景:
无范围索引的应用场景:
有范围索引示例:
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6]])
rows = np.array([0, 1, 2])
cols = np.array([1, 0, 1])
selected_elements = arr[rows, cols]
print(selected_elements) # 输出: [2 3 6]
无范围索引示例:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# 获取第二行的所有元素
second_row = arr[1, :]
print(second_row) # 输出: [4 5 6]
# 获取所有行的第三列元素
third_column = arr[:, 2]
print(third_column) # 输出: [3 6 9]
问题:在使用有范围索引时,可能会遇到索引超出数组边界的情况。
原因:
解决方法:
np.clip
函数将索引值限制在合法范围内。import numpy as np
arr = np.array([[1, 2], [3, 4]])
rows = np.array([0, 2]) # 第二个索引2超出了数组的行范围
# 使用np.clip限制索引值
clipped_rows = np.clip(rows, 0, arr.shape[0] - 1)
selected_elements = arr[clipped_rows, :]
print(selected_elements) # 输出: [[1 2] [3 4]]
通过这种方式,可以有效地避免索引越界的问题,确保程序的稳定性和可靠性。
领取专属 10元无门槛券
手把手带您无忧上云