【发布时间】:2014-07-17 16:36:10
【问题描述】:
我有一个 4 列的 numpy 数组,想要选择第 1、3 和 4 列,其中第二列的值满足特定条件(即固定值)。我尝试首先只选择行,但通过以下方式选择所有 4 列:
I = A[A[:,1] == i]
有效。然后我进一步尝试(类似于我非常熟悉的matlab):
I = A[A[:,1] == i, [0,2,3]]
这是行不通的。怎么做?
示例数据:
>>> 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]]
我现在正在使用这个:
I = A[A[:,1] == i]
I = I[:, [0,2,3]]
但我认为必须有更好的方法来做到这一点......(我习惯了 MATLAB)
【问题讨论】:
-
A[A[:,1] == i][0,2,3]也不起作用? -
I = A[A[:,1] == i][0,2,3] --> IndexError: too many indices
-
除此之外,我必须承认我也不会真正理解索引,这与 matlab 非常不同......
-
@tim:能否请您发布数组以及您期望的输出?
-
@Ankur Ankan:编辑成问题。