python - Numpy where function multiple conditions -
i have array of distances called dists. want select dists between 2 values. wrote following line of code that:
dists[(np.where(dists >= r)) , (np.where(dists <= r + dr))]
however selects condition
(np.where(dists <= r + dr))
if commands sequentially using temporary variable works fine. why above code not work, , how work?
cheers
the best way in your particular case change 2 criteria 1 criterion:
dists[abs(dists - r - dr/2.) <= dr/2.]
it creates 1 boolean array, , in opinion easier read because says, is dist
within dr
or r
? (though i'd redefine r
center of region of interest instead of beginning, r = r + dr/2.
) doesn't answer question.
the answer question:
don't need where
if you're trying filter out elements of dists
don't fit criteria:
dists[(dists >= r) & (dists <= r+dr)]
because &
give elementwise and
(the parentheses necessary).
or, if want use where
reason, can do:
dists[(np.where((dists >= r) & (dists <= r + dr)))]
why:
reason doesn't work because np.where
returns list of indices, not boolean array. you're trying and
between 2 lists of numbers, of course doesn't have true
/false
values expect. if a
, b
both true
values, a , b
returns b
. saying [0,1,2] , [2,3,4]
give [2,3,4]
. here in action:
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) , np.where(dists <= r+dr) out[235]: (array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),)
what expecting compare boolean array, example
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)
now can call np.where
on combined boolean array:
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. ])
or index original array boolean array using fancy indexing
in [241]: dists[(dists >= r) & (dists <= r + dr)] out[241]: array([ 5. , 5.5, 6. ])
Comments
Post a Comment