a = np.array([0,10,20,30,40,50,60,70])
indices = np.array([0,2,4,6])
a[indices]
Output: array([ 0, 20, 40, 60])
A = np.array([[1,1,1],
[2,2,2],
[3,3,3]])
indices = np.array([0,2])
A[indices]
Output: array([[1, 1, 1],[3, 3, 3]])
Whether it is an array or a matrix, you can directly extract them. Note that the indices must be in np.array format.
-
Using the at function to perform operations at specified positions
For example, if we have a large matrix and want to add a set of values to certain columns:
C = np.zeros((5,3))
temp = np.ones((2,3))
print('C:\n',C)
print('temp:\n',temp)
Let’s see what C and temp look like:
C:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
temp:
[[1. 1. 1.]
[1. 1. 1.]]
Next, we want to add the values of the two vectors in temp to rows 0 and 2 of C, we can simply write:
np.add.at(C,[0,2],temp)
C
array([[1., 1., 1.],
[0., 0., 0.],
[1., 1., 1.],
[0., 0., 0.],
[0., 0., 0.]])
Look! It’s that convenient! Here, add
can be replaced with various other operations.
Recommended Reading
2021 iFLYTEK - Vehicle Loan Default Prediction Competition Top 1 Solution (Python Code)
10 Complete Python Operations for Clustering Algorithms
Why Use MSE for Regression Problems?
Stability Analysis of Time Series Feature Correlation Coefficients (with Code)
Summary of Time Series Prediction Methods: From Theory to Practice (with Kaggle Classic Competition Solutions)