如何从numpy数组中删除一些特定的元素?说我有
import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9])
然后我想从a中删除3,4,7。我所知道的是这些值的下标(index=[2,3,6])。
如何从numpy数组中删除一些特定的元素?说我有
import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9])
然后我想从a中删除3,4,7。我所知道的是这些值的下标(index=[2,3,6])。
当前回答
如果不知道索引,就不能使用logical_and
x = 10*np.random.randn(1,100)
low = 5
high = 27
x[0,np.logical_and(x[0,:]>low,x[0,:]<high)]
其他回答
过滤不需要的部分:
import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9])
a = a[(a!=3)&(a!=4)&(a!=7)]
如果你有一个要删除的索引列表:
to_be_removed_inds = [2,3,6]
a = np.array([1,2,3,4,5,6,7,8,9])
a = a[[x for x in range(len(a)) if x not in to_be_removed]]
按值删除:
modified_array = np.delete(original_array, np.where(original_array == value_to_delete))
如果我们知道要删除的元素的索引,使用np.delete是最快的方法。但是,为了完整起见,让我添加另一种“删除”数组元素的方法,使用在np.isin的帮助下创建的布尔掩码。该方法允许我们通过直接指定或通过索引来删除元素:
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
按指数移除:
indices_to_remove = [2, 3, 6]
a = a[~np.isin(np.arange(a.size), indices_to_remove)]
按元素删除(不要忘记重新创建原来的a,因为它在前一行中被重写了):
elements_to_remove = a[indices_to_remove] # [3, 4, 7]
a = a[~np.isin(a, elements_to_remove)]
列表理解也是一种有趣的方法。
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
index = np.array([2, 3, 6]) #index is changed to an array.
out = [val for i, val in enumerate(a) if all(i != index)]
>>> [1, 2, 5, 6, 8, 9]
如果不知道索引,就不能使用logical_and
x = 10*np.random.randn(1,100)
low = 5
high = 27
x[0,np.logical_and(x[0,:]>low,x[0,:]<high)]