2017-07-07 5 views
0

numpy.where()は、1つの条件では動作しますが、2つの条件では動作しません。二つの条件についてはこのnumpy.where()アプローチは、1つではなく2つの条件に適合させることができますか?

import numpy as np 

a = np.array([1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 1, 1, 1, 2, 4, 5]) 
i, = np.where(a < 2) 
print(i) 
>> [ 0 5 8 10 11 12] ## indices where a[i] = 1 

:1つの条件については

# condition = (a > 1 and a < 3) 
# i, = np.where(condition) 
i, = np.where(a > 1 and a < 3) 
print(i) 
>> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 

私はa.any()a.all()in this other SO postをよく読んで、これは私ので、私の目的のために動作しません。単一のブール値ではなく、条件に合致するすべてのインデックスが必要です。

これを2つの条件に適合させる方法はありますか?

+0

あなたは 'if'、またはこの場合はPythonの' and'のようなスカラーコンテキストでブール配列を使用する場合、この値はエラーが生成されます。代わりに '&'を使用してください。 '()'でオペレータの順序を制御します。 – hpaulj

答えて

2

使用np.where((a > 1) & (a < 3))

関連する問題