[英]How can I replace all numbers of an array with all numbers of an other array except of the zeros (Python, numpy)?
I have two arrays like these: 我有两个像这样的数组:
a = [[1,2,-3],[4,5,-6],[7,8,9]]
b = [[2,-5,0],[0,4,8],[-2,1,0]]
Every number of "a" should be replaced with the one from "b", except of those, where the number of "b" is 0: “ a”的每个数字都应替换为“ b”中的一个数字,但“ b”的数字为0的数字除外:
result = [[2,-5,-3],[4,4,8],[-2,1,9]]
My current solution takes way too long: 我当前的解决方案花费的时间太长:
for row in range(len(b)):
for column in range(len(b[row])):
if b[row][column] != 0 or b[row][column] != -0:
a[row][column] = b[row][column]
Btw. 顺便说一句。 is the "b[row][column] != -0" necessary? “ b [row] [column]!= -0”是否必要? Since there are sometimes "0"s and sometimes "-0"s in b. 由于b中有时有“ 0”,有时有“ -0”。
Is there a fast way? 有没有快速的方法? Thanks. 谢谢。
Just use np.where()
只需使用np.where()
a = np.array(a)
b = np.array(b)
a = np.where(b == 0, a, b)
If you want to get fancy and save memory, use np.place()
如果您想花哨并节省内存,请使用np.place()
np.place(a, b != 0, b[b != 0])
EDIT: Since 0 == -0
evaluates True
, you don't need any other checks 编辑:由于0 == -0
计算为True
,因此您不需要任何其他检查
一种可能性:
a[np.where(b !=0)] = b[np.where(b !=0)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.