📜  Numpy index 索引(1)

📅  最后修改于: 2023-12-03 15:33:13.986000             🧑  作者: Mango

Numpy Indexing

Indexing is the means by which elements of arrays can be accessed and modified. Indexing in NumPy is based on the python indexing scheme with zero-based indexing.

One-Dimensional Arrays

One-dimensional arrays can be indexed using a single index similar to python lists.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr[0])   # output : 1
print(arr[2])   # output : 3

Negative indexing can also be used to access elements from the end of the array.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr[-1])  # output : 5
print(arr[-3])  # output : 3
Multi-Dimensional Arrays

Multi-dimensional arrays can be indexed using multiple indices separated by commas, and the indices are specified in the order of the axes of the array.

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[0, 1])    # output : 2
print(arr[1, 2])    # output : 6

Slicing can also be used with multi-dimensional arrays. A colon separates the start and stop indices for each dimension, and multiple colons can be used to skip over some portions of dimensions.

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr[0:2, 1:3])   # output : [[2 3], [5 6]]

Boolean indexing can also be used to select elements based on a condition.

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])
bool_arr = arr % 2 == 0   # create a boolean array of even numbers
print(bool_arr)           # output : [False, True, False, True, False, True]
print(arr[bool_arr])      # output : [2, 4, 6]
Fancy Indexing

Fancy indexing is a mechanism in NumPy that allows indexing an array with another array or a sequence of indices.

import numpy as np

arr = np.array([2, 3, 4, 5, 6])
indices = np.array([0, 2, 4])    # select elements at index 0, 2, and 4
print(arr[indices])             # output : [2, 4, 6]

Fancy indexing can also be used with multi-dimensional arrays.

import numpy as np

arr = np.array([[1, 2], [3, 4], [5, 6]])
row_indices = np.array([0, 1, 2])
col_indices = np.array([0, 1])
print(arr[row_indices, col_indices])   # output : [1, 4, 6]
Conclusion

Indexing is a powerful tool in NumPy that enables access and manipulation of elements in arrays based on a wide range of criteria. Familiarizing oneself with indexing is an important step towards mastering data manipulation in NumPy.