当组已知时,从numpy ndarray中选择行

时间:2013-02-18 14:25:30

标签: python numpy

我有一个numpy数组x和一个标记cls列表,它保留了x的顺序,并记录了来自x的每个元素所属的类。例如,对于两个不同的类01

x = [47 21 16 19 38]
cls = [0 0 1 0 1]

意味着47, 21, 19属于一起,16, 38也是如此。

是否有一种pythonic方法可以按类从x中选择元素?

现在我正在做

for clusterId in np.unique(cls):
indices = [i for i in range(len(cls)) if cls[i]==clusterId]
print 'Class ', clusterId
for idx in indices:
    print '\t', x[idx,].tolist()

但我无法相信没有更优雅的东西。

1 个答案:

答案 0 :(得分:5)

cls非常适合构造布尔索引数组:

>>> import numpy as np
>>> x = np.array([47, 21, 16, 19, 38])
>>> cls = np.array([0, 0, 1, 0, 1],dtype=bool)
>>> x[cls]
array([16, 38])
>>> x[~cls]
array([47, 21, 19])

请注意,如果cls已经不是布尔数组,您可以使用ndarray.astype将其设为一个:

>>> cls = np.array([0, 0, 1, 0, 1])
>>> x[cls]  #Not what you want
array([47, 47, 21, 47, 21])
>>> x[cls.astype(bool)]  #what you want.
array([16, 38])

在一般情况下,你有一个cls数组,并且你只想挑选出具有该索引的元素:

>>> x[cls == 0]
array([47, 21, 19])
>>> x[cls == 1]
array([16, 38])

要查找您拥有的所有课程,您可以使用np.unique(cls)