Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select specific columns in NumPy array using colon notation

I have a 40000 by 60 Numpy array, and I want to sth like this:

mat[:,[0:13,19:23,23:31,39:59]]

Obviously, it does not work. Is there a smarter way to do this than concatenation?

like image 615
Gordon Cai Avatar asked Jun 05 '17 19:06

Gordon Cai


People also ask

How do I select a specific column in a NumPy array?

Use NumPy array indexing to extract specific columsUse the syntax array[:, [i, j]] to extract the i and j indexed columns from array . Like lists, NumPy arrays use zero-based indexes. Use array[:, i:j+1] to extract the i through j indexed columns from array .

What does [: :] mean on NumPy arrays?

The [:, :] stands for everything from the beginning to the end just like for lists. The difference is that the first : stands for first and the second : for the second dimension. a = numpy. zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])

How do I select part of an array in NumPy?

To select an element from Numpy Array , we can use [] operator i.e. It will return the element at given index only.

What does colon do in NumPy?

A colon by itself means fetch everything. A colon on the right side of an index means everything after the specified index. A colon on the left side of an index means everything before, but not including, the index. And if we use a negative index, it means get elements from the end, going backwards.


1 Answers

Use np.r_ -

mat[:,np.r_[0:13,19:23,23:31,39:59]]

Sample run -

In [48]: mat = np.random.rand(100,1000)

In [50]: mat[:,np.r_[0:13,19:23,23:31,39:59]].shape
Out[50]: (100, 45)

In [51]: 13+4+8+20
Out[51]: 45
like image 145
Divakar Avatar answered Sep 19 '22 18:09

Divakar