有没有更好的方法(更简单,更易读,更符合Python风格,更高效等)可以从数组中删除多个值?比如下面这种方法:
请注意,
import numpy as np
# The array.
x = np.linspace(0, 360, 37)
# The values to be removed.
a = 0
b = 180
c = 360
new_array = np.delete(x, np.where(np.logical_or(np.logical_or(x == a,
x == b),
x == c)))
对于这个问题,一个好的答案应产生与上面代码相同的结果(即新数组new_array
),但可能在处理浮点数之间的等式时比上面的代码更好。
额外奖励
有人能解释一下为什么这会产生错误的结果吗?
In [5]: np.delete(x, x == a)
/usr/lib/python2.7/dist-packages/numpy/lib/function_base.py:3254: FutureWarning: in the future insert will treat boolean arrays and array-likes as boolean index instead of casting it to integer
"of casting it to integer", FutureWarning)
Out[5]:
array([ 20., 30., 40., 50., 60., 70., 80., 90., 100.,
110., 120., 130., 140., 150., 160., 170., 180., 190.,
200., 210., 220., 230., 240., 250., 260., 270., 280.,
290., 300., 310., 320., 330., 340., 350., 360.])
值 0 和 10 都已被删除,而不仅仅是 0 (a
)。
注意,x == a
如预期一样(因此问题在于 np.delete
内部):
In [6]: x == a
Out[6]:
array([ True, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False], dtype=bool)
请注意,
np.delete(x, np.where(x == a))
也可以得到正确的结果。因此,我认为np.delete
无法处理布尔索引。
delete
。它指定了obj: slice、int 或 int 数组
(没有布尔值)。 - hpaulj