Extract multiple elements with Numpy array

There are many times when you want to retrieve non-contiguous elements

>>> a = np.array([1,2,3,4])
>>> indices = [0,2]
>>> a[indices]
array([1,3])

Useful when you want to replace elements

>>> a = np.array([1,2,3,4])
>>> indices = [0,1,3,2]
>>> a[indices]
array([1, 2, 4, 3])

Note that if you pass set instead of list, an error will occur or unexpected behavior will occur. Be especially careful when using multidimensional arrays.

>>> a = np.array([[1,2,3],[3,4,5],[5,6,7]])
>>> a
array([[1, 2, 3],
       [3, 4, 5],
       [5, 6, 7]])
>>> indices = [0,2]
>>> a[indices]
array([[1, 2, 3],
       [5, 6, 7]])
>>> indices = (0,2)
>>> a[indices]
3

Recommended Posts

Extract multiple elements with Numpy array
Extract array elements and indexes in descending order with numpy
Extract non-numeric elements with pandas.DataFrame
Extract elements other than a specific index with Numpy
Extract specific multiple columns with pandas
NumPy array manipulation (3)
NumPy array manipulation (1)
Multiple selections with Jupyter
[Python] Create structured array (store heterogeneous data with NumPy)
Various ways to extract columns in a NumPy array
Calculate Entropy for arrays with zero elements in Numpy
Moving average with numpy
Merge array with PyYAML
python numpy array calculation
Learn with Cheminformatics NumPy
Matrix concatenation with Numpy
Hamming code with numpy
Regression analysis with NumPy
Convert elements of numpy array from float to int
Extract EXIF with sips
Extend NumPy with Rust
Get Python list elements with multiple indexes (number) Simple method
I want to judge the authenticity of the elements of numpy array
How to extract other than a specific index with Numpy
Sum of multiple numpy arrays (sum)
Kernel regression with Numpy only
CNN implementation with just numpy
Artificial data generation with numpy
Multiple regression analysis with Keras
Extract Twitter data with CSV
[Python] Calculation method with numpy
Try matrix operation with NumPy
Diffusion equation animation with NumPy
Debt repayment simulation with numpy
Stick strings together with Numpy
Manipulate multiple proxies with Squid
Stumble story with Python array
Create a python numpy array
Handle numpy arrays with f2py
Use OpenBLAS with numpy, scipy
Multidimensional array calculation without Numpy
Animate multiple graphs with matplotlib
Control multiple robots with jupyter-lab
Python3 | Getting Started with numpy
Extract peak values with scipy
About Numpy array and asarray
Implementing logistic regression with NumPy