If you've got a boolean array you can do direct selection based on that like so:

>>> a = np.array([True, True, True, False, False])
>>> b = np.array([1,2,3,4,5])
>>> b[a]
array([1, 2, 3])

To go along with your initial example you could do the following:

>>> a = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> b = np.array([[False,True,False],[True,False,False],[False,False,True]])
>>> a[b]
array([2, 4, 9])

You can also add in an arange and do direct selection on that, though depending on how you're generating your boolean array and what your code looks like YMMV.

>>> a = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> a[np.arange(len(a)), [1,0,2]]
array([2, 4, 9])
Answer from Slater Victoroff on Stack Overflow
๐ŸŒ
IncludeHelp
includehelp.com โ€บ python โ€บ numpy-selecting-specific-column-index-per-row-by-using-a-list-of-indexes.aspx
Python - NumPy selecting specific column index per row by using a list of indexes
We need to select some specific column based on the index which is itself an element of the list given to use. For this purpose, we will use np.arrange method() which will take a total length of the array and the index list and returns evenly spaced values within a given interval.
Discussions

Select One Element in Each Row of a Numpy Array by Column Indices - Stack Overflow
164 NumPy selecting specific column index per row by using a list of indexes More on stackoverflow.com
๐ŸŒ stackoverflow.com
python 3.x - Numpy Selecting Elements given row and column index arrays - Stack Overflow
I have row indices as a 1d numpy array and a list of numpy arrays (list as same length as the size of the row indices array. I want to extract values corresponding to these indices. How can I do it... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - numpy, Select elements in rows by 1d indexes array - Stack Overflow
And let we have array of indices in the each ROW. For example: ... Because in line [0,1,2] take element with index 1, in line [3,4,5] get element with index 2, in line [6,7,8] get element with index 1. I'm confused, and can't take elements this way using standard numpy indexing. More on stackoverflow.com
๐ŸŒ stackoverflow.com
June 7, 2021
python - How can I filter NumPy array by list of indices? - Stack Overflow
I have a NumPy array, filtered__rows, comprised of LAS data [x, y, z, intensity, classification]. I have created a cKDTree of points and have found the nearest neighbors, query_ball_point, which i... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Top answer
1 of 4
151

As Toan suggests, a simple hack would be to just select the rows first, and then select the columns over that.

>>> a[[0,1,3], :]            # Returns the rows you want
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [12, 13, 14, 15]])
>>> a[[0,1,3], :][:, [0,2]]  # Selects the columns you want as well
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

[Edit] The built-in method: np.ix_

I recently discovered that numpy gives you an in-built one-liner to doing exactly what @Jaime suggested, but without having to use broadcasting syntax (which suffers from lack of readability). From the docs:

Using ix_ one can quickly construct index arrays that will index the cross product. a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]].

So you use it like this:

>>> a = np.arange(20).reshape((5,4))
>>> a[np.ix_([0,1,3], [0,2])]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

And the way it works is that it takes care of aligning arrays the way Jaime suggested, so that broadcasting happens properly:

>>> np.ix_([0,1,3], [0,2])
(array([[0],
        [1],
        [3]]), array([[0, 2]]))

Also, as MikeC says in a comment, np.ix_ has the advantage of returning a view, which my first (pre-edit) answer did not. This means you can now assign to the indexed array:

>>> a[np.ix_([0,1,3], [0,2])] = -1
>>> a    
array([[-1,  1, -1,  3],
       [-1,  5, -1,  7],
       [ 8,  9, 10, 11],
       [-1, 13, -1, 15],
       [16, 17, 18, 19]])
2 of 4
102

Fancy indexing requires you to provide all indices for each dimension. You are providing 3 indices for the first one, and only 2 for the second one, hence the error. You want to do something like this:

>>> a[[[0, 0], [1, 1], [3, 3]], [[0,2], [0,2], [0, 2]]]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

That is of course a pain to write, so you can let broadcasting help you:

>>> a[[[0], [1], [3]], [0, 2]]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

This is much simpler to do if you index with arrays, not lists:

>>> row_idx = np.array([0, 1, 3])
>>> col_idx = np.array([0, 2])
>>> a[row_idx[:, None], col_idx]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])
๐ŸŒ
thisPointer
thispointer.com โ€บ home โ€บ python โ€บ select rows / columns by index in numpy array
Select Rows / Columns by Index in NumPy Array - thisPointer
November 12, 2023 - This selects columns 2 and 3 (1:3 slice). To select sub 2d Numpy Array we can pass the row & column index range in [] operator i.e.
๐ŸŒ
Codegive
codegive.com โ€บ blog โ€บ numpy_select_columns_by_index.php
Numpy select columns by index
To select multiple non-contiguous columns, you pass a list or a NumPy array of column indices in the second position of the square brackets.
๐ŸŒ
Iditect
iditect.com โ€บ faq โ€บ python โ€บ numpy-selecting-specific-column-index-per-row-by-using-a-list-of-indexes.html
NumPy selecting specific column index per row by using a list of indexes
If you need to modify the original array, you'll need to assign the selected values back to the corresponding positions in the array. Remember that indexing is zero-based in Python, so the column indexes in column_indexes should be valid indices for the columns in your array. NumPy select specific column index per row from array
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ reference โ€บ generated โ€บ numpy.take.html
numpy.take โ€” NumPy v2.5 Manual
The indices of the values to extract. Also allow scalars for indices. ... The axis over which to select values. By default, the flattened input array is used.
Top answer
1 of 4
41

You can choose from given array using numpy.choose which constructs an array from an index array (in your case select_id) and a set of arrays (in your case input_array) to choose from. However you may first need to transpose input_array to match dimensions. The following shows a small example:

In [101]: input_array
Out[101]: 
array([[ 3, 14],
       [12,  5],
       [75, 50]])

In [102]: input_array.shape
Out[102]: (3, 2)

In [103]: select_id
Out[103]: [0, 1, 1]

In [104]: output_array = np.choose(select_id, input_array.T)

In [105]: output_array
Out[105]: array([ 3,  5, 50])
2 of 4
9

(because I can't post this as a comment on the accepted answer)

Note that numpy.choose only works if you have 32 or fewer choices (in this case, the dimension of your array along which you're indexing must be of size 32 or smaller). Additionally, the documentation for numpy.choose says

To reduce the chance of misinterpretation, even though the following "abuse" is nominally supported, choices should neither be, nor be thought of as, a single array, i.e., the outermost sequence-like container should be either a list or a tuple.

The OP asks:

  1. Is there a better way to get the output_array from the input_array and select_id?
    • I would say, the way you originally suggested seems the best out of those presented here. It is easy to understand, scales to large arrays, and is efficient.
  2. Can we get rid of range(input_array.shape[0])?
    • Yes, as shown by other answers, but the accepted one doesn't work in general so well as what the OP already suggests doing.
Find elsewhere
๐ŸŒ
ProjectPro
projectpro.io โ€บ recipes โ€บ select-elements-from-numpy-array-in-python
How to Select Columns in NumPy Array using np.select? -
February 22, 2024 - You can use array slicing with a specified column index. ... The expression arr[:, 1:3] selects all rows (indicated by :) and the second and third columns (columns with index 1 and 2).
๐ŸŒ
Earth Data Science
earthdatascience.org โ€บ home
Slice (or Select) Data From Numpy Arrays | Earth Data Science - Earth Lab
September 23, 2019 - Just like for the one-dimensional numpy array, you use the index [1,2] for the second row, third column because Python indexing begins with [0], not with [1] On this page, you will use indexing to select elements within one-dimensional and two-dimensional numpy arrays, a selection process referred to as slicing. Begin by importing the necessary Python packages and downloading and importing the data into numpy arrays.
๐ŸŒ
Kanoki
kanoki.org โ€บ numpy-get-ith-column-and-specific-column-row-data-from-array
Numpy get ith column and specific column and row data from an array | kanoki
October 6, 2022 - Ellipsis expands to the number of:objects needed for the selection tuple to index all dimensions. ... We want the 2nd and 3rd column of the array a. ... We want the last column of the array, we could use negative indices for indexing from the end of the array ... The output array is 1D of shape 5. We could also change the shape of the output array by using newaxis.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-access-a-numpy-array-by-column
How to access a NumPy array by column - GeeksforGeeks
April 23, 2023 - Prerequisite: Numpy module The following article discusses how we can access different columns of multidimensional Numpy array.
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.2 โ€บ reference โ€บ generated โ€บ numpy.take.html
numpy.take โ€” NumPy v2.2 Manual
The indices of the values to extract. Also allow scalars for indices. ... The axis over which to select values. By default, the flattened input array is used.
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.1 โ€บ reference โ€บ generated โ€บ numpy.take.html
numpy.take โ€” NumPy v2.1 Manual
The indices of the values to extract. New in version 1.8.0. Also allow scalars for indices. ... The axis over which to select values. By default, the flattened input array is used.
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ user โ€บ basics.indexing.html
Indexing on ndarrays โ€” NumPy v2.5 Manual
Integer array indexing allows selection of arbitrary items in the array based on their N-dimensional index. Each integer array represents a number of indices into that dimension.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-access-a-numpy-array-by-column
How to access a NumPy array by column?
Use the colon ":" operator to select all rows and specify the column index ? import numpy as np # Create a sample NumPy array array = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # Access the third column (index 2) column = array[:, 2] print("Third column:") print(column) ... Fancy indexing allows you to access multiple columns simultaneously by passing an array of column indices ?