English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Array indexing is equivalent to accessing array elements.
You can access array elements by referencing their index numbers.
The indexing of NumPy arrays starts with 0, which means the index of the first element is 0, and the index of the second element is 1And so on.
Let's take a look at the index operation of one-dimensional arrays first:
>>> import numpy as np >>> arr = np.array([1, 2, 3, 4]) >>> print(arr[0]) # Print the first element of the array 1 >>> print(arr[1]) # Print the second element of the array 2 >>> print(arr[2] + arr[3]) # Sum of the third and fourth elements of the array 7
To access elements in a two-dimensional array, we can use a comma-separated integer to represent the dimension and index of the element.
Let's take a look at the index operation of two-dimensional arrays first:
>>> import numpy as np >>> arr = np.array([1,2,3,4,5], [6,7,8,9,10]) >>> print('2nd_element_on 1st_dim: ', arr[0, 1]) # Access the second element in the first dimension 2nd_element_on 1st_dim: 2 >>> print('5th_element_on 2nd_dim: ', arr[1, 4]) # Access the fifth element in the second dimension: 5th_element_on 2nd_dim: 10
To access 3-We can use comma-separated integers to represent the dimension and index of the elements in the D array.
>>> import numpy as np >>> arr = np.array([[[1, 2, 3], [4, 5, 6]]7, 8, 9], [10, 11, 12]]) >>> print(arr[0, 1, 2]) 6
The first number represents the first dimension, which contains two arrays:
[[1, 2, 3], [4, 5, 6]] and [[7, 8, 9], [10, 11, 12]], because we have selected 0So the remaining first array is:[[1, 2, 3], [4, 5, 6]].
The second number represents the second dimension, which also contains two arrays:[1, 2, 3]and [4, 5, 6]Because we have selected 1So the remaining second array is: [4, 5, 6].
The third number represents the third dimension, which contains three values:4,5,6
Since we have selected 2Therefore, the final value obtained is the third one:6
Negative indexing starts from the end of the array.
Print the last element in the second dimension:
>>> import numpy as np >>> arr = np.array([1,2,3,4,5], [6,7,8,9,10]) >>> print('The last element in the second dimension: ', arr[1, -1]) The last element in the second dimension: 10