繁体   English   中英

NumPy 1D阵列切片

[英]NumPy 1D array slicing

我有一个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个值,但是可以使用类似的语法跳过几个值吗?

感谢您的任何帮助!

你可能想要np.delete

>>> np.delete(a, [4, 5, 10, 11])
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

您可以使用布尔数组索引

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更改a != 0导致布尔数组的其他条件。

使用布尔或掩码索引数组

>>> 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])

我看到两个选择:

  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]) 
  2. 使用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]) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM