选择某些行(满足条件),但只选择Python/Numpy中的某些列

tim*_*tim 10 python numpy

我有一个有4列的numpy数组,想要选择第1,3和4列,其中第二列的值满足某个条件(即固定值).我试图首先只选择行,但通过以下所有4列:

I = A[A[:,1] == i]
Run Code Online (Sandbox Code Playgroud)

哪个有效.然后我进一步尝试(类似于我非常清楚的matlab):

I = A[A[:,1] == i, [0,2,3]]
Run Code Online (Sandbox Code Playgroud)

这不起作用.怎么做?


示例数据:

 >>> A = np.array([[1,2,3,4],[6,1,3,4],[3,2,5,6]])
 >>> print A
 [[1 2 3 4]
  [6 1 3 4]
  [3 2 5 6]]
 >>> i = 2

 # I want to get the columns 1, 3 and 4 for every row which has the value i in the second column. In this case, this would be row 1 and 3 with columns 1, 3 and 4:
 [[1 3 4]
  [3 5 6]]
Run Code Online (Sandbox Code Playgroud)

我现在正在使用这个:

I = A[A[:,1] == i]
I = I[:, [0,2,3]]
Run Code Online (Sandbox Code Playgroud)

但我认为必须有一个更好的方法...(我习惯于MATLAB)

Joh*_*nck 20

>>> a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
>>> a
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

>>> a[a[:,0] > 3] # select rows where first column is greater than 3
array([[ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

>>> a[a[:,0] > 3][:,np.array([True, True, False, True])] # select columns
array([[ 5,  6,  8],
       [ 9, 10, 12]])

# fancier equivalent of the previous
>>> a[np.ix_(a[:,0] > 3, np.array([True, True, False, True]))]
array([[ 5,  6,  8],
       [ 9, 10, 12]])
Run Code Online (Sandbox Code Playgroud)

有关模糊的说明np.ix_(),请参阅/sf/answers/951989041/

最后,我们可以通过给出列号列表而不是繁琐的布尔掩码来简化:

>>> a[np.ix_(a[:,0] > 3, (0,1,3))]
array([[ 5,  6,  8],
       [ 9, 10, 12]])
Run Code Online (Sandbox Code Playgroud)


Tah*_*aha 5

如果您不想使用布尔位置而是索引,则可以这样编写:

A[:, [0, 2, 3]][A[:, 1] == i]
Run Code Online (Sandbox Code Playgroud)

回到您的示例:

>>> A = np.array([[1,2,3,4],[6,1,3,4],[3,2,5,6]])
>>> print A
[[1 2 3 4]
 [6 1 3 4]
 [3 2 5 6]]
>>> i = 2
>>> print A[:, [0, 2, 3]][A[:, 1] == i]
[[1 3 4]
 [3 5 6]]
Run Code Online (Sandbox Code Playgroud)

说真的