gpt4 book ai didi

python - 使用一个数组过滤掉另一个数组

转载 作者:行者123 更新时间:2023-12-01 02:33:40 59 4
gpt4 key购买 nike

如何使用一个数组过滤掉另一个具有非零值的数组?

from numpy import array

a = array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])

b = array([[0, 0, 1, 0, 0],
[0, 0, 2, 0, 0],
[0, 0, 3, 0, 0],
[0, 0, 4, 0, 0],
[0, 0, 5, 0, 0]])

预期结果:

array([[ 0, 0, 2,  0, 0],
[ 0, 0, 7, 0, 0],
[ 0, 0, 12, 0, 0],
[ 0, 0, 17, 0, 0],
[ 0, 0, 22, 0, 0]])

谢谢

最佳答案

如果你想要一个新数组,最简单的方法是带有 3 个参数的 np.where:

>>> import numpy as np
>>> np.where(b, a, 0)
array([[ 0, 0, 2, 0, 0],
[ 0, 0, 7, 0, 0],
[ 0, 0, 12, 0, 0],
[ 0, 0, 17, 0, 0],
[ 0, 0, 22, 0, 0]])

如果您想就地更改a,您可以使用基于b的 bool 索引:

>>> a[b == 0] = 0
>>> a
array([[ 0, 0, 2, 0, 0],
[ 0, 0, 7, 0, 0],
[ 0, 0, 12, 0, 0],
[ 0, 0, 17, 0, 0],
[ 0, 0, 22, 0, 0]])

关于python - 使用一个数组过滤掉另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46501637/

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