Basic indexing and slicing
- ndarrays can be indexed using the standard Python x[obj] syntax, where x is the array and obj the selection.
- There are different kinds of indexing available depending on obj: basic indexing, advanced indexing, and field access.
- Single element indexing works exactly like Python sequences.
- It is 0-based and accepts negative indices for indexing from the end of the array.
- It is not necessary to separate each dimension’s index into its own set of square brackets.
- The basic concept of slicing extends Python’s basic slicing concept to N dimensions.
- A slice object constructed by start: stop step notation inside of brackets.
- The simplest case of indexing:- N integers returns an array scalar representing the corresponding item.
- In Python, all indices are zero-based, the valid range is 0 where d is the i-th element of the shape of the array.
- Negative indices are interpreted as counting from the end of the array (i.e., if n, it means ).
- Facilitate the easy matching of array shapes with expressions and in assignments.
- Ellipsis expands to the number of objects needed for the selection tuple to index all dimensions.
- Example:-
- This is equivalent to:
The dots (...) represent as many colons as needed to
produce a complete indexing tuple. For example, if x is an array with 5 axes, then
·
x[1, 2, ...] is equivalent to x[1, 2, :, :, :],
·
x[..., 3] to x[:, :, :, :, 3] and
· x[4, ..., 5, :] to x[4, :, :, 5, :].
>>> c = np.array([[[ 0, 1, 2], # a 3D array (two stacked 2D arrays)
... [ 10, 12, 13]],
... [[100, 101, 102],
... [110, 112, 113]]])
>>> c.shape
(2, 2, 3)
>>> c[1, ...] # same as c[1, :, :] or c[1]
array([[100, 101, 102],
[110, 112, 113]])
>>> c[..., 2] # same as c[:, :, 2]
array([[ 2, 13],
[102, 113]])
Iteration in multidimensional arrays is done with the first axis:
>>> for row in b:
... print(row)
...
[0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]
if wants to perform an operation on each element in the array, use the flat attribute which is an iterator over all the elements of the array:
>>> for element in b.flat:
... print(element)
...
0
1
2
3
10
11
12
13
20
21
22
23
30
31
32
33
40
41
42
43
0 Comments