Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract all columns but one from an array (or matrix) in python?

Given a numpy 2d array (or a matrix), I would like to extract all the columns but the i-th.

E. g. from

1 2 3 4 2 4 6 8 3 6 9 12 

I would like to have, e.g.

1 2 3 2 4 6 3 6 9 

or

1 2 4 2 4 8 3 6 12 

I cannot find a pythonic way to do this. I now that you can extract given columns by simply

a[:,n] 

or

a[:,[n,n+1,n+5]] 

But what about extracting all of them but one?

like image 256
Ferdinando Randisi Avatar asked Jun 04 '14 00:06

Ferdinando Randisi


People also ask

How do I separate an array of columns in Python?

hsplit() function | Python. numpy. hsplit() function split an array into multiple sub-arrays horizontally (column-wise). hsplit is equivalent to split with axis=1, the array is always split along the second axis regardless of the array dimension.

How do you extract an element from an array in Python?

extract() function returns elements of input_array if they satisfy some specified condition. Parameters : array : Input array. User apply conditions on input_array elements condition : [array_like]Condition on the basis of which user extract elements.


2 Answers

Since for the general case you are going to be returning a copy anyway, you may find yourself producing more readable code by using np.delete:

>>> a = np.arange(12).reshape(3, 4) >>> np.delete(a, 2, axis=1) array([[ 0,  1,  3],        [ 4,  5,  7],        [ 8,  9, 11]]) 
like image 69
Jaime Avatar answered Oct 06 '22 10:10

Jaime


Use a slice that excludes the last element.

In [19]: a[:,:-1] Out[19]:  array([[1, 2, 3],        [2, 4, 6],        [3, 6, 9]]) 

If you want something other than the last element I'd just build a list to select with.

In [20]: selector = [x for x in range(a.shape[1]) if x != 2] In [21]: a[:, selector] Out[21]:  array([[ 1,  2,  4],        [ 2,  4,  8],        [ 3,  6, 12]]) 

http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

like image 25
chrisb Avatar answered Oct 06 '22 08:10

chrisb