python numpy array index and slice operation method
- 2020-12-22 17:42:00
- OfStack
Introduction of NumPy -
NumPy is an Python package. It stands for "Numeric Python". It is a library of multidimensional array objects and a collection of routines used to process arrays.
Numeric, the predecessor of NumPy, was developed by Jim Hugunin. Another package, Numarray, was also developed, which has a few additional features. In 2005, Travis Oliphant created the NumPy package by integrating the features of Numarray into the Numeric package. This open source project has many contributors.
NumPy operation
With NumPy, developers can do the following:
The & # 8226; Arithmetic and logical operations of arrays.
The & # 8226; Fourier transform and routines for graphic manipulation.
The & # 8226; Operations relating to linear algebra. NumPy has built-in functions for linear algebra and random number generation.
The numpy library multidimensional arrays are very similar in type to lists, and also have indexing and slicing functions:
Index: The process of getting the element at a particular position in an array
Slice: The process of getting a subset of an array's elements
1.1 dimensional array
# To prepare 1 An array
arr1=np.array(np.arange(9))
arr1
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
# The index
arr[-1] #8
arr1[arr1.size-2] #7
arr1[arr1.size-9] #0
# slice : [start:end:step]
arr1[1:4] # Left open and right closed
arr1[1:5:2] #array([1,3])
arr1[::-1] # Take all of them backwards, -1 It becomes the step size
2.2 dimensional array
# To prepare 1 a 2 Dimensional array
arr2=np.array([
np.arange(1,4),
np.arange(5,8)
])
arr2
array([[1, 2, 3],
[5, 6, 7]])
# The index
arr2[0][2] # 3
arr2[0,2] # 3
# slice
arr2[0,] # array([1,2,3])
arr2[0,::] # Same as above
arr2[0,0:3] #array([1,2])
3. Multidimensional arrays
arr4=np.arange(1,25).reshape(2,3,4)
arr4
array([[[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]],
[[13, 14, 15, 16],
[17, 18, 19, 20],
[21, 22, 23, 24]]])
arr4[1][2][2] # 23
arr4[1,1,1] #18
arr3[1,1,] # array([17,18,19,20])
arr4[1,1,::] # Same as above
arr4[1,1,::-1] # array([20, 19, 18, 17])
arr4[0,1:3]
#array([[ 5, 6, 7, 8],
#[ 9, 10, 11, 12]])
arr4[:1,1] #array([ 6, 18])
b[1,:,2] #array([15, 19, 23])
b[1,...]
#array([[13, 14, 15, 16],
# [17, 18, 19, 20],
# [21, 22, 23, 24]])
b[0,::-1,-1] #array([12, 8, 4])
b[:,:,-1][::-1][:,-1] #array([24, 12])
conclusion