简体   繁体   English

删除满足2个条件的2D numpy数组中的元组

[英]Remove tuples in a 2D numpy array that satisfy 2 conditions

So I have a numpy array of tuples and I want to remove all tuples where the first value is less than 0 or the second element is greater than a number, n. 所以我有一个元组的numpy数组,我想删除第一个值小于0或第二个元素大于数字n的所有元组。
So if n = 10 and we had this array: 所以如果n = 10并且我们有这个数组:

[[-1, 5], [3, 11], [-4, 20]]

It would become this: 它将变成这样:

[[]]

I'm guessing I need to use np.delete and np.where in a smart way? 我猜我需要以一种聪明的方式使用np.deletenp.where吗?

Thanks in advance. 提前致谢。

You can use something like the following: 您可以使用如下所示的内容:

>>> import numpy as np
>>> A = np.array([[-1, 5], [3, 11], [-4, 20]])
>>> mask = (A[:,0]>0) & (A[:,1] > 10)
>>> A[mask]
array([[ 3, 11]])

The idea is to express your condition using an expression as in mask . 这个想法是使用mask的表达式来表达您的病情。

You can solve this using logical indexing. 您可以使用逻辑索引解决此问题。 I'm guessing in your example you meant that 我猜在你的例子中,你的意思是

[[-1, 5], [3, 11], [-4, 20]]

would become 会成为

[]

Since you said that the conditions are: 由于您说的条件是:

I want to remove all tuples where the first value is less than 0 or the second element is greater than a number , n. 我想删除 第一个值小于0 第二个元素大于数字 n的所有元组。

>>> import numpy as np
>>> arr = np.array([[-1, 5], [3, 11], [-4, 20]])
>>> arr[~((arr[:,0] < 0) | (arr[:,1] > 10))]
array([], shape=(0, 2), dtype=int64)

Basically it's all down to expressing your logical requirement as the combination (through | and & ) of different logical masks. 基本上,将逻辑要求表达为不同逻辑掩码的组合(通过|& )。

The ~ takes the inverse of the mask, since you said you wanted to delete elements that match your criteria. ~表示掩码的倒数,因为您说过要删除符合条件的元素。 A better example of this method working is this: 这种方法工作的一个更好的例子是:

>>> import numpy as np
>>> arr = np.array([[-1, 5], [1, 1], [3, 11], [-4, 20], [2, 9]])
>>> arr[~((arr[:,0] < 0) | (arr[:,1] > 10))]
array([[1, 1], [2, 9]])

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

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