numpy where

np.where(condition, x, y) #

如果是一维数组, 相当于[xv if c else yv for (c, xv, yv) in zip(condition, x, y)].

>>> aa = np.arange(10)
>>> np.where(aa, 1, -1)
array([-1,  1,  1,  1,  1,  1,  1,  1,  1,  1])
>>> np.where(aa > 5,1,-1)
array([-1, -1, -1, -1, -1, -1,  1,  1,  1,  1])

np.where(condition) #

只有条件condition, 则输出满足条件元素的坐标. 这里的坐标以tuple的形式给出, 通常原数组有多少维, 输出的tuple中就包含几个数组, 分别对应符合条件元素的各维坐标.

>>> a = np.array([2,4,6,8,10])
>>> np.where(a > 5)
(array([2, 3, 4]),)
>>> a[np.where(a > 5)]
array([ 6,  8, 10])

& | #

condition与或逻辑用&/|表示.

mask[np.where((low_freq < fre) & (fre < high_freq))] = 0
mask[np.where((-low_freq > fre) | (fre > -high_freq))] = 1