如何从复杂的 numpy 数组中选择一行?



我已经阅读了10-20个不同的问题/答案,但找不到这样的例子。 我想从 numpy 数组中选择行,如下所示:

test = [ [ [0], np.zeros((250,250)), np.array([0,0]) ],
[ [0], np.zeros((250,250)), np.array([1,1]) ],
[ [1], np.zeros((250,250)), np.array([2,2]) ],
[ [2], np.zeros((250,250)), np.array([2,2]) ],
[ [2], np.zeros((250,250)), np.array([2,2]) ]
]

现在将列表转换为 numpy 数组并打印第一列:

nptest = np.array(test)
print (nptest[:,0])
> output is: [[0] [0] [1] [2] [2]]

现在尝试只选择第一个元素 = 1 的行

just_1s = nptest[nptest[:,0] == 1]
print (just_1s)
> output is []

我不明白这个输出。

在我的实际问题集中,我有 100 个,每个都有任意数量的行,第一列的值为 0-15。使用上面的示例数据,所需的结果将是三个 numpy 数组,如下所示:

just_0s = [[ [0], np.zeros((250,250)), np.array([0,0]) ],
[ [0], np.zeros((250,250)), np.array([1,1]) ]
]
just_1s = [[ [1], np.zeros((250,250)), np.array([2,2]) ]]
just_2s = [[ [2], np.zeros((250,250)), np.array([2,2]) ],
[ [2], np.zeros((250,250)), np.array([2,2]) ]
]

使用列表理解

just_1s = [el for el in nptest if el[0] == [1]]

但实际上没有必要使用nd.arrays,使用原始列表是可以

just_1s = [el for el in test if el[0] == [1]]


如果你的观点是为什么一个人在做nptest[nptest[:, 0] == [1]]时会[](请注意,我测试[1]而不是1(,我不知道。因为根据我(和山姆·马里内利(的说法,它应该奏效。我们错了。


但如果仔细观察,似乎
just_1s = nptest[ nptest[:,0].tolist().index([1]) ]

工作正常,但前提是[1]是唯一的。情况并非如此,例如[2].

这是列表生成一个 (5,3( 对象数组:

In [47]: nptest=np.array(test)
In [49]: nptest.shape
Out[49]: (5, 3)
In [50]: nptest.dtype
Out[50]: dtype('O')
In [51]: nptest[:,0]
Out[51]: array([list([0]), list([0]), list([1]), list([2]), list([2])], dtype=object)

第一列是列表的数组 (1d(。 在我的较新的numpy版本中,这更明确。

对列表数组甚至列表进行相等性测试并不容易。 在尝试了几件事后,我发现了这个:

In [52]: arow = nptest[:,0]
In [56]: [x[0]==1 for x in arow]
Out[56]: [False, False, True, False, False]
In [57]: mask = [x[0]==1 for x in arow]
In [58]: nptest[mask,:]
Out[58]: 
array([[list([1]),
array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],
[ 0.,  0.,  0., ...,  0.,  0.,  0.],
[ 0.,  0.,  0., ...,  0.,  0.,  0.],
..., 
[ 0.,  0.,  0., ...,  0.,  0.,  0.],
[ 0.,  0.,  0., ...,  0.,  0.,  0.],
[ 0.,  0.,  0., ...,  0.,  0.,  0.]]),
array([2, 2])]], dtype=object)

或者我们可以将列表数组转换为数字数组:

In [60]: np.array(arow.tolist())
Out[60]: 
array([[0],
[0],
[1],
[2],
[2]])
In [61]: np.array(arow.tolist())==1
Out[61]: 
array([[False],
[False],
[ True],
[False],
[False]], dtype=bool)

或者测试[1]而不是 1。 列表匹配列表,而不是其内容。

In [64]: [x==[1] for x in arow]
Out[64]: [False, False, True, False, False]

我相信问题出在表达式nptest[:, 0] == 1. 您已经证明nptest[:, 0]按预期返回[[0], [0], [1], [2], [2]]。 您可以看到这些值都不等于1,因此nptest[nptest[:, 0] == 1]将为空。 请尝试nptest[nptest[:, 0] == [1]]

最新更新