gpt4 book ai didi

python - 如果行(或列)中的所有值不满足给定条件,则删除对称数组中的行和列

转载 作者:太空宇宙 更新时间:2023-11-03 16:02:16 25 4
gpt4 key购买 nike

我有一个稀疏的对称数组,如果给定行(和列)的所有单独条目不满足某个阈值条件,我将尝试删除该数组的行和列。例如,如果

min_value = 2
a = np.array([[2, 2, 1, 0, 0],
[2, 0, 1, 4, 0],
[1, 1, 0, 0, 1],
[0, 4, 0, 1, 0],
[0, 0, 1, 0, 0]])

我想保留其值至少为 2 或以上的行(和列),这样在上面的示例中就会产生

a_new = np.array([2, 2, 0],
[2, 0, 4],
[0, 4, 1]]

所以我会丢失第 3 行和第 5 行(以及第 3 和第 5 列),因为每个条目都少于 2。我已经查看了 How could I remove the rows of an array if one of the elements of the row does not satisfy a condition? , Delete columns based on repeat value in one row in numpy arrayDelete a column in a multi-dimensional array if all elements in that column satisfy a condition但标记的解决方案不符合我想要实现的目标。

我正在考虑执行类似的操作:

a_new = []
min_count = 2

for row in a:
for i in row:
if i >= min_count:
a_new.append(row)
print(items)
print(temp)

但这不起作用,因为它不会删除坏列,并且如果有两个(或更多)实例的值大于阈值,它会多次追加一行。

最佳答案

您可以使用矢量化解决方案来解决该问题,如下所示 -

# Get valid mask
mask = a >= min_value

# As per requirements, look for ANY match along rows and cols and
# use those masks to index into row and col dim of input array with
# 1D open meshes from np.ix_ and thus select a 2D slice out of it
out = a[np.ix_(mask.any(1),mask.any(0))]

更简单的表达方式是先选择行,然后选择列,如下所示 -

a[mask.any(1)][:,mask.any(0)]

滥用输入数组的对称性,它会简化为 -

mask0 = (a>=min_value).any(0)
out = a[np.ix_(mask0,mask0)]

示例运行 -

In [488]: a
Out[488]:
array([[2, 2, 1, 0, 0],
[2, 0, 1, 4, 0],
[1, 1, 0, 0, 1],
[0, 4, 0, 1, 0],
[0, 0, 1, 0, 0]])

In [489]: min_value
Out[489]: 2

In [490]: mask0 = (a>=min_value).any(0)

In [491]: a[np.ix_(mask0,mask0)]
Out[491]:
array([[2, 2, 0],
[2, 0, 4],
[0, 4, 1]])
<小时/>

或者,我们可以使用有效掩码的行和列索引,如下所示 -

r,c = np.where(a>=min_value)
out = a[np.unique(r)[:,None],np.unique(c)]

再次滥用对称性,简化版本将是 -

r = np.unique(np.where(a>=min_value)[0])
out = a[np.ix_(r,r)]

r 也可以通过混合 bool 运算来获得 -

r = np.flatnonzero((a>=min_value).any(0))

关于python - 如果行(或列)中的所有值不满足给定条件,则删除对称数组中的行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40228453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com