假设我有一个numpy数字数组(例如:整数)。我想在序列中删除数字
k
。目前我正在编写一个for循环来实现此功能,但这似乎是一个过度杀伐的方法。有没有更简单的方法来实现它?一般而言,如果我需要删除不止一个数字怎么办。k
。目前我正在编写一个for循环来实现此功能,但这似乎是一个过度杀伐的方法。有没有更简单的方法来实现它?一般而言,如果我需要删除不止一个数字怎么办。A
,包含要删除数字的数组为B
,您可以使用np.in1d
获取A
中与B
匹配的掩码,然后使用反转版本的掩码来映射A
并获得所需的输出。这是实现的代码示例:A[~np.in1d(A,B).reshape(A.shape)]
示例运行 -
In [14]: A
Out[14]: array([3, 2, 1, 4, 3, 3, 2, 2, 4, 1])
In [15]: B
Out[15]: array([2, 4])
In [16]: A[~np.in1d(A,B).reshape(A.shape)]
Out[16]: array([3, 1, 3, 3, 1])
对于一个二维输入数组的情况,你将得到一个一维数组作为输出,就像这样 -
In [21]: A
Out[21]:
array([[3, 3, 3, 4, 0, 4],
[2, 4, 4, 4, 4, 3],
[1, 2, 4, 4, 3, 1],
[0, 3, 1, 4, 1, 1]])
In [22]: B
Out[22]: array([2, 4])
In [23]: A[~np.in1d(A,B).reshape(A.shape)]
Out[23]: array([3, 3, 3, 0, 3, 1, 3, 1, 0, 3, 1, 1, 1])
如果您想检查单个标量值。在numpy中,当您将向量与标量值进行比较时,您会得到一个由True/False
值组成的数组,其中每个元素表示标量值与该元素的比较结果。例如 -
In [15]: a = np.random.randint(10,100, (100,))
In [16]: a
Out[16]:
array([63, 19, 84, 89, 89, 76, 18, 16, 57, 65, 25, 31, 17, 20, 25, 14, 27,
70, 79, 87, 82, 59, 50, 86, 20, 42, 81, 58, 32, 23, 68, 12, 19, 98,
11, 90, 76, 55, 40, 66, 83, 64, 46, 65, 94, 64, 91, 89, 18, 44, 59,
52, 51, 22, 32, 94, 88, 38, 31, 91, 47, 76, 62, 43, 89, 41, 76, 81,
50, 53, 76, 97, 49, 91, 39, 81, 52, 94, 21, 77, 94, 96, 28, 57, 38,
10, 55, 57, 55, 41, 15, 14, 91, 69, 80, 43, 83, 31, 21, 76])
In [17]: a != 15
Out[17]:
array([ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
False, True, True, True, True, True, True, True, True, True], dtype=bool)
bool
数组来索引您的原始数组,该数组返回索引数组中具有 True
的值。这是 布尔数组索引
的一部分。例如 -In [18]: a[a != 15]
Out[18]:
array([63, 19, 84, 89, 89, 76, 18, 16, 57, 65, 25, 31, 17, 20, 25, 14, 27,
70, 79, 87, 82, 59, 50, 86, 20, 42, 81, 58, 32, 23, 68, 12, 19, 98,
11, 90, 76, 55, 40, 66, 83, 64, 46, 65, 94, 64, 91, 89, 18, 44, 59,
52, 51, 22, 32, 94, 88, 38, 31, 91, 47, 76, 62, 43, 89, 41, 76, 81,
50, 53, 76, 97, 49, 91, 39, 81, 52, 94, 21, 77, 94, 96, 28, 57, 38,
10, 55, 57, 55, 41, 14, 91, 69, 80, 43, 83, 31, 21, 76])
a[a != <某个数字>]
吗? - Anand S Kumar