我有一个NumPy数组,如:
a = np.array([1,2,3,4,0,0,5,6,7,8,0,0,9,10,11,12])
在某些位置选择除值(在我的示例中为0)之外的所有值的最有效方法是什么?
所以我需要得到一个数组:
[1,2,3,4,5,6,7,8,9,10,11,12]
我知道如何使用[::n]
构造跳过第n个值,但是可以使用类似的语法跳过几个值吗?
感谢您的帮助!
答案 0 :(得分:4)
您可能需要np.delete
:
>>> np.delete(a, [4, 5, 10, 11])
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
答案 1 :(得分:1)
您可以使用Boolean array indexing:
import numpy as np
a = np.array([1,2,3,4,0,0,5,6,7,8,0,0,9,10,11,12])
print a[a != 0]
# Output: [ 1 2 3 4 5 6 7 8 9 10 11 12]
您可以将a != 0
更改为导致布尔数组的其他条件。
答案 2 :(得分:1)
使用boolean or mask index array:
>>> a = np.array([1,2,3,4,0,0,5,6,7,8,0,0,9,10,11,12])
>>> a[a != 0]
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
答案 3 :(得分:1)
我看到两个选项:
如果要获取可在多个阵列上使用的索引向量:
import numpy as np
#your input
a = np.array([1,2,3,4,0,0,5,6,7,8,0,0,9,10,11,12])
#indices of elements that you want to remove (given)
idx = [4,5,10,11]
#get the inverted indices
idx_inv = [x for x in range(len(a)) if x not in idx]
a[idx_inv]
此输出:
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
使用np.delete
:
import numpy as np
#your input
a = np.array([1,2,3,4,0,0,5,6,7,8,0,0,9,10,11,12])
#indices of elements that you want to remove (given)
idx = [4,5,10,11]
np.delete(a,idx)
输出:
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])