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

时间:2017-07-31 21:23:32

标签: python 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]) ]
          ]

3 个答案:

答案 0 :(得分:1)

使用list comprehension

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

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

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

<小时/> 如果您的观点是 ,为什么在执行[] 时会得到nptest[nptest[:, 0] == [1]](请注意,我测试的是[1]而不是1 }), 我不知道 。因为根据我(和Sam Marinelli)它应该有效。我们错了。

<小时/> 但是,如果看得更近,它似乎

just_1s = nptest[ nptest[:,0].tolist().index([1]) ]

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

答案 1 :(得分:1)

这是列表产生一个(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]

答案 2 :(得分:0)

我认为问题在于nptest[:, 0] == 1这个词。您已经显示nptest[:, 0]按预期返回[[0], [0], [1], [2], [2]]。您可以看到这些值都不等于1,因此nptest[nptest[:, 0] == 1]将为空。请改为nptest[nptest[:, 0] == [1]]