简体   繁体   English

如何用除零(Python,numpy)以外的其他数组的所有数字替换数组的所有数字?

[英]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.

相关问题 如何将零添加到用户输入数组的所有数字并将所有数字转换为相同的数字? - how can i add zeros to all the numbers of the user entered array and convert all numbers to the same digits? 有一个带有一些数字的数组。 除了一个,所有数字都相等。 我怎么才能在 python 中找到那个数字? - There is an array with some numbers. All numbers are equal except for one. How i can found only that number in python? 用零替换 numpy 数组中低于阈值的数字 - Replace numbers below threshold in numpy array with zeros 如何替换除python中的特定数字以外的所有数字? - How to replace all numbers, except specific numbers in python? 如何删除列表中除 1 个数字(Python)之外的所有数字? - How can I remove all the numbers in a list except for 1 number (Python)? 将 numpy 数组中的所有零替换为一个 - Replace all Zeros by Ones in a numpy array 将多维数组中的所有元素除以数字数组 Numpy Python - Dividing all elements in a multidimensional array by an array of numbers Numpy Python 替换numpy数组中的数字 - Replace numbers in numpy array 如何使用包含要访问的索引号的数组获取numpy数组中的所有值 - How to obtain all the values in a numpy array using an array containing index numbers I want to access 如何将二维 numpy 数组中的所有数字转换为字符串? - How to convert all numbers in a 2d numpy array to strings?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM