あなたの特定のケースではただ一つの基準にあなたの2つの基準を変更することです最善の方法:
dists[abs(dists - r - dr/2.) <= dr/2.]
それは唯一のブール配列を作成し、私の意見では簡単です「はdr
またはr
の中にdist
と表示されています(r
を最初の部分ではなく、あなたの関心領域の中心に再定義しますが、r = r + dr/2.
)しかし、あなたの質問には答えません。
あなたの質問への答え:
dists[(dists >= r) & (dists <= r+dr)]
:あなたは自分の基準に適合しないdists
の要素をフィルタリングしようとしている場合は、実際にwhere
を必要としない
&
は要素ごとにand
となります(括弧が必要です)。
それとも、あなたには、いくつかの理由でwhere
を使いたいならば、あなたが行うことができます:
dists[(np.where((dists >= r) & (dists <= r + dr)))]
理由:np.where
はリストを返すので、それが動作しない理由がある
ブール値の配列ではなく、インデックスの値。数字の2つのリストの間にand
を取得しようとしていますが、当然True
/False
という値はありません。 a
とb
が両方ともTrue
の値の場合、a and b
はb
を返します。だから[0,1,2] and [2,3,4]
のようなものは、あなたに[2,3,4]
を与えるだけです。
In [239]: np.where((dists >= r) & (dists <= r + dr))
Out[239]: (array([10, 11, 12]),)
In [240]: dists[np.where((dists >= r) & (dists <= r + dr))]
Out[240]: array([ 5. , 5.5, 6. ])
:例今
In [236]: dists >= r
Out[236]:
array([False, False, False, False, False, False, False, False, False,
False, True, True, True, True, True, True, True, True,
True, True], dtype=bool)
In [237]: dists <= r + dr
Out[237]:
array([ True, True, True, True, True, True, True, True, True,
True, True, True, True, False, False, False, False, False,
False, False], dtype=bool)
In [238]: (dists >= r) & (dists <= r + dr)
Out[238]:
array([False, False, False, False, False, False, False, False, False,
False, True, True, True, False, False, False, False, False,
False, False], dtype=bool)
あなたが組み合わせブールアレイ上np.where
を呼び出すことができるため、
In [230]: dists = np.arange(0,10,.5)
In [231]: r = 5
In [232]: dr = 1
In [233]: np.where(dists >= r)
Out[233]: (array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]),)
In [234]: np.where(dists <= r+dr)
Out[234]: (array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),)
In [235]: np.where(dists >= r) and np.where(dists <= r+dr)
Out[235]: (array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),)
何を比較するのに期待していたことは、単にブール配列した:ここではアクションであります
またはブール値配列を使用して元の配列にインデックスを付けるだけです。fancy indexing
In [241]: dists[(dists >= r) & (dists <= r + dr)]
Out[241]: array([ 5. , 5.5, 6. ])
この場合、反復する必要はありません。 NumPyにはブールインデックスがあります。 – M456