How to implement indexing and slicing of ndarray arrays?
Index: the process of getting elements at a specific location in an array
Slicing: the process of getting a subset of array elements
Import numpy as np
One-dimensional array
The indexes and slices of an one-dimensional array are similar to the lists in python
Index: if the number of elements is n, the subscript of the index can be expressed as [0force 1, 2, 2] or [- n, 1),-2, 2, 1]
Print (indexing and slicing of one-dimensional array of '8percent' 8)
If the number of elements is n, then the subscript of the index can be expressed as [0meme1meme2meme2] or [- nmae1] or [- nmae1),-(nmae2),-2mermer1].
Ar1 = np.array ([5,6,7,8,9])
Print (ar1 [4]) # Index starts from left to right with subscript 0
Print (ar1 [- 2]) # Index decreases from right to left from subscript-1, the rightmost index is-1, and the adjacent index is-2
Slices: slices can be divided with three-element colons
Ar1 [starting number: ending number (excluding): step size], starting number defaults to 0, termination number defaults to n, and step size defaults to 1
It is still a ndarray array
B = ar1 [1:4:2]
Print (b)
Print (type (b))
Multidimensional array
Ar2 = np.arange (24). Reshape ((2,3,4))
Print (indexing and slicing of multidimensional arrays of '8percent' and'8')
The index of a multidimensional array, with one index value for each dimension, separated by commas-R2 [index on ax0, index on ax1, index on ax2], and each dimension index is the same as one-dimensional 0~n-1 or-nasty Mel 1.
Print (ar2)
Print (ar2 [1,1,2])
Print (ar2 [- 1,-2,-2])
Multidimensional array slices are separated by commas. Each dimension is the same as a dimensional slice, separated by three colons. If there is only one: the entire dimension is selected.
Print (ar2 [:, 1:3,:])
Print (ar2 [:, 1:3,:: 2])
Print (ar2 [:, 1,-3])
Indexed array: an array is used as an index, usually an one-dimensional array (each element represents the corresponding dimensional index)
1. Boolean index
Boolean array: as the name implies, an array whose element type is a Boolean value can also be an one-dimensional or multi-dimensional array
For example: bool_arr1 = np.array ([True, False, False,True])
The following array definition is also a Boolean array
Names = np.array (['Liu',' Zhang', 'Li',' Wang', 'Sun',' Zong', 'Kong'])
Bool_arr2 = names = = 'Zhang'
Bool_arr2 is array [False True False False False False False]
If you want to get bool_arr1, then bool_arr1 = (names = = 'Liu') | (names = =' Kong')
Similarly, with &, non, is not equal to! =, > =,