Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select specific columns in numpy array?

Supposing I have 20x100 numpy array. I want to select all columns except say 50th. So I was following this thread Extracting specific columns in numpy array but it didn't help. I tried using

 x=Z[:,[:49,51:]] 

but was giving error. In R it is easy to do this

x=Z[,c(1:49,51:100)] 

But could not figure out in Python. Please help. Thanks

like image 615
Gaurav Chawla Avatar asked Dec 27 '15 15:12

Gaurav Chawla


People also ask

How do I select a specific column from a NumPy array very important?

We can use [][] operator to select an element from Numpy Array i.e. Example 1: Select the element at row index 1 and column index 2. Or we can pass the comma separated list of indices representing row index & column index too i.e.

How do I sort a NumPy array by a specific column?

NumPy arrays can be sorted by a single column, row, or by multiple columns or rows using the argsort() function. The argsort function returns a list of indices that will sort the values in an array in ascending value.

How do you select a specific element in a NumPy array?

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


1 Answers

One way to get an R-like syntax here would be to use np.r_:

>>> Z = np.arange(2000).reshape(20, 100)
>>> Z.shape
(20, 100)
>>> x = Z[:,np.r_[:49,50:100]]
>>> x.shape
(20, 99)
>>> x[0,48:52]
array([48, 50, 51, 52])

and we see that the 50th column (with number 49) is missing from x.

like image 138
DSM Avatar answered Sep 30 '22 23:09

DSM