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]])
Answer from Praveen on Stack Overflow
🌐
ProjectPro
projectpro.io › recipes › select-elements-from-numpy-array-in-python
How to Select Columns in NumPy Array using np.select? -
February 22, 2024 - The expression arr[:, 1:3] selects all rows (indicated by :) and the second and third columns (columns with index 1 and 2). Adjust the column indices in the slice as needed. You can use array slicing with a step size to select every nth element ...
🌐
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 - To select a column, pass the column index along with the rows information in the [] operator of NumPy Array. ... It will return a complete column at given index. To select multiple columns use,
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.select.html
numpy.select — NumPy v2.5 Manual
>>> x = np.arange(6) >>> condlist = [x<3, x>3] >>> choicelist = [-x, x**2] >>> np.select(condlist, choicelist, 42) array([ 0, -1, -2, 42, 16, 25]) When multiple conditions are satisfied, the first one encountered in condlist is used.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-access-a-numpy-array-by-column
How to access a NumPy array by column - GeeksforGeeks
April 23, 2023 - import numpy as np array = [[1, 13, 6], [9, 4, 7], [19, 16, 2]] # defining array arr = np.array(array) print('printing 0th row') print(arr[0, :]) print('printing 2nd column') print(arr[:, 2]) # multiple columns or rows can be selected as well print('selecting 0th and 1st row simultaneously') print(arr[:,[0,1]]) Output : printing 0th row [ 1 13 6] printing 2nd column [6 7 2] selecting 0th and 1st row simultaneously [[ 1 13] [ 9 4] [19 16]] Transpose of the given array using the .T property and pass the index as a slicing index to print the array.
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]])
🌐
IncludeHelp
includehelp.com › python › extracting-specific-columns-in-numpy-array.aspx
Extract Specific Columns in NumPy Array (3 Best Ways)
For example, you want to extract columns 1 and 3 of all rows. Follow the below-given syntax: ... Here, arr is the name of the input array and res is the subarray in which the result will be stored. # Import numpy import numpy as np # Creating a numpy 2D array arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) # Printing original array print("Original array:\n", arr, "\n") # Extracting specific columns # using using Ellipsis res = arr[..., 1:3] # Printing specific columns print("Specific columns:\n", res)
Find elsewhere
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › program-to-access-different-columns-of-a-multidimensional-numpy-array
Program to access different columns of a multidimensional Numpy array | GeeksforGeeks
November 1, 2020 - Accessing a NumPy-based array by a specific Column index can be achieved by indexing. NumPy follows standard 0-based indexing in Python.
🌐
Finxter
blog.finxter.com › home › learn python blog › how to extract specific numpy columns? 5 best ways
How to Extract Specific NumPy Columns? 5 Best Ways - Be on the Right Side of Change
July 31, 2022 - Above, an np.array() function is used to declare a 2D (two-dimensional) NumPy array containing a small sampling of integers. This saves to data. Next, a subset of the above data is extracted containing all rows and columns 1, 3, and 5 using slicing (data[:, 1:6:2]) as follows:
🌐
ACM
helloacm.com › home › python › how to extract multiple columns from numpy 2d matrix?
How to Extract Multiple Columns from NumPy 2D Matrix? | Algorithms, Blockchain and Cloud
November 7, 2014 - The correct way is to first select the rows and then return the wanted columns: arr[arr[:,0]==2,:][:,[1,2]] array([[0, 1], [0, 1], [4, 0]]) Two deep-copies will be made. –EOF (The Ultimate Computing & Technology Blog) — · 196 words Last ...
🌐
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 ?
🌐
Quora
quora.com › How-do-I-extract-specific-columns-from-a-NumPy-array-in-Python
How to extract specific columns from a NumPy array in Python - Quora
Answer (1 of 3): The simplest way is probably to use the standard indexing system with slicing. An element in a numpy array can be specified by using its indices normally such as arr[row, col] However, NumPy also allows for slicing, e.g. arr[1:4, 2], which returns the elements in column 2 (the ...
🌐
NumPy
numpy.org › doc › 2.3 › reference › generated › numpy.select.html
numpy.select — NumPy v2.3 Manual
>>> x = np.arange(6) >>> condlist = [x<3, x>3] >>> choicelist = [-x, x**2] >>> np.select(condlist, choicelist, 42) array([ 0, -1, -2, 42, 16, 25]) When multiple conditions are satisfied, the first one encountered in condlist is used.
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.select.html
numpy.select — NumPy v2.6.dev0 Manual
>>> x = np.arange(6) >>> condlist = [x<3, x>3] >>> choicelist = [-x, x**2] >>> np.select(condlist, choicelist, 42) array([ 0, -1, -2, 42, 16, 25]) When multiple conditions are satisfied, the first one encountered in condlist is used.