我有一个形状为
numpy 数组。(500,12)
我想做的就是检查偶数列是否具有正值,例如:value > 0
。如果是这样,我想在数组中删除整行。
a = a[a[:,1] < 0, :]
这将消除所需的行,但只查看第二列。我希望它也能检查第4列、第6列、第8列等等。
使用上述方法,有没有一种可以做到这一点的方法?
mask = (a[:, np.arange(1, a.shape[1], 2)] < 0).all(axis=1)
out = a[mask]
解释:
选择奇数列的位置,比较其值:
np.arange(1, a.shape[1], 2) # a.shape[1] gives the number of columns
# array([ 1, 3, 5, 7, 9, 11])
接下来,我们根据这些索引对数组进行子集划分,并通过提供 axis = 1
来检查这些列下的值是否小于零,执行列方向的检查并返回一个包含删除其余行后减少行数的数组。
虽然可能不是最有效的方法,但您可以对所有行使用逐元素与&
:
a = a[<b>(a[:,1]<0)&(a[:,3]<0)&(a[:,5]<0)&(a[:,7]<0)&(a[:,9]<0)&(a[:,11]<0)</b>,:]
functools.reduce
:<b>from functools import reduce</b>
a = a[<b>reduce(lambda x,y:x&y,(a[:,i]<0 for i in range(1,12,2)))</b>,:]
如果事先不完全知道 shape
,可以使用 .shape[1]
:
from functools import reduce
a = a[reduce(lambda x,y:x&y,(a[:,i]<0 for i in range(1,<b>a.shape[1]</b>,2))),:]
b[i]=abs(min(a[:,0::2][:,i]))
现在唯一需要做的就是将这些值添加到它们各自所在的整个列中。 - Mati Malika = [row for row in a if all(row[j] <= 0 for j in range(0, len(row), 2))]
m = (arr > 0) # check if positive; this is what you want to keep
m = arr.ix[:,1::2] # select only the even columns
m = arr.any(axis=1) # and check if any of them is true
所以简单来说:
arr[(arr > 0)[:,1::2].all(axis=1),:]
all
而不是 any
吗? - Willem Van Onsem如果不使用循环,就没有单个命令可以帮助您实现目标。我建议遍历所有行,然后执行此操作。
<=
吗? - Willem Van Onsem