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

Bog*_*scu 2 python numpy

我有一个numpy数组x和一个cls保留顺序的标签列表x,并记录每个元素x属于的类.例如,对于两个不同的类0和1:

x = [47 21 16 19 38]
cls = [0 0 1 0 1]
Run Code Online (Sandbox Code Playgroud)

意思是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()
Run Code Online (Sandbox Code Playgroud)

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

mgi*_*son 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])
Run Code Online (Sandbox Code Playgroud)

请注意,如果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])
Run Code Online (Sandbox Code Playgroud)

在一般情况下,如果您有一个cls数组,并且只想选择具有该索引的元素:

>>> x[cls == 0]
array([47, 21, 19])
>>> x[cls == 1]
array([16, 38])
Run Code Online (Sandbox Code Playgroud)

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