3

numpy 配列との順序を保持するxタグのリストがあり、各要素が属するクラスを記録します。たとえば、2 つの異なるクラスとの場合:clsxx01

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()

しかし、これほどエレガントなものはないなんて信じられません。

4

1 に答える 1

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)

于 2013-02-18T14:27:59.523 に答える