如何比较多个2D numpy数组上的非零值?

2024-10-03 17:16:26 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个填充了随机整数的二维数组。 我希望第一个数组保留值为leq5的所有索引,第二个数组保留值为leq6的所有索引。为简单起见,所有其他索引都可以设置为零。你知道吗

table1 = np.array(([1,3],[5,7]))
table2  = np.array(([2,4],[6,8]))

print table1
print table2 ,'\n'

table1_tol_i = np.where(table1[:,:] > 5)
table1[table1_tol_i] = 0
print table1 

table2_tol_i = np.where(table2[:,:] > 4)
table2[table2_tol_i] = 0
print table2, '\n'

[[1 3]
 [5 7]]
[[2 4]
 [6 8]] 

[[1 3]
 [5 0]]
[[2 4]
 [0 0]]

然后我只想保留两个表都有非零值的索引。我想要

[[1 3]
 [0 0]]
[[2 4]
 [0 0]]

我试过下面的方法,但没有给我想要的

nonzero_i = (np.where(table1 != 0) and (np.where(table2 != 0 )))
print table1[nonzero_i]
print table2[nonzero_i]

[1 3]
[2 4]

Tags: and方法np整数数组wherearrayprint
3条回答

获取表1为0的所有索引:

table1_zeros = np.where(table1[:,:] == 0)

获取表2为0的所有索引:

table2_zeros = np.where(table2[:,:] == 0)

将两个表上的值都设置为0:

table1[table1_zeros] = 0
table1[table2_zeros] = 0
table2[table1_zeros] = 0
table2[table2_zeros] = 0

你也可以用tableX_tol_i代替tableX_zeros,一步到位。你知道吗

table1 = np.array(([1,3],[5,7]))
table2  = np.array(([2,4],[6,8]))
table3  = np.zeros((2,2))
for k in range(0,2):
    for j in range(0,2):
        if table1[k][j] > 5:
            table1[k][j] = 0
        if table1[k][j] <= 5:
            table1[k][j] = table1[k][j]
        if table2[k][j] > 6:
            table2[k][j] = 0
        if table2[k][j] <= 6:
            table2[k][j] = table2[k][j]
x=0
y=0
for k in range(0,2):
    for j in range(0,2):
        if table1[k][j] != 0:
            table3[x,y] = table1[k][j] 
            x = x+1
x=0
y=1
for k in range(0,2):
    for j in range(0,2):
        if table2[k][j] != 0:
            table3[x,y] = table2[k][j] 
            x = x+1   
print (table3)   

我认为这是最简单的方法,你想要什么。如果数组大小更改,可以修改代码。你知道吗

只保留两个表都有非零值的索引-这就是为什么当您用nonzero_i索引到table1table2时,只返回第一行(只包含非零值)。你知道吗

这种逻辑可以通过构造boolean index array来更简单地表达:

# boolean array that is True wherever both table1 & table2 are nonzero
valid = (table1 != 0) & (table2 != 0)

# or alternatively:
# valid = np.logical_and(table1, table2)

您可以使用它直接索引到table1table2。你知道吗


看起来你实际上想做的是给table1table2为0的任何位置赋值。你知道吗

如果需要副本,可以使用^{}np.where(condition, val_where_true, val_where_false)语法:

print(repr(np.where(valid, table1, 0)))
# array([[1, 3],
#        [0, 0]])

print(repr(np.where(valid, table2, 0)))
# array([[2, 4],
#        [0, 0]])

或者如果您想修改table1table2,您可以这样做

table1[~valid] = 0

table2[~valid] = 0

~是“按位not”运算符,它反转布尔索引数组)。你知道吗

相关问题 更多 >