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

Given an numd 2d array (or matrix), I would like to extract all columns except the i-th.

E. from

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

I would like to have for example

 1 2 3 2 4 6 3 6 9 

or

 1 2 4 2 4 8 3 6 12 

I can not find a pythonic way to do this. Now I can extract these columns just

 a[:,n] 

or

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

But what about extracting all of them except one?

+6
source share
3 answers

Since for the general case, you will still return a copy, you can create more readable code 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]]) 
+12
source

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 different from the last item, I just create a list for selection 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

+15
source

Take a look at the numpy extended slice

 >>> import numpy as np >>> a = np.array([[1,2,3,4], [2,4,6,8], [3,6,9,12]]) >>> a[:,np.array([True, True, False, True])] array([[ 1, 2, 4], [ 2, 4, 8], [ 3, 6, 12]]) 
+5
source

Source: https://habr.com/ru/post/970284/


All Articles