根据条件合并具有相同维度的两个数组



我有两个相同维度的数组:

a = [
[1, 1, 1, 1],
[1, 0, 0, 1],
[1, 0, 0, 1],
[1, 1, 1, 1], ]
b = [
[0, 1, 1, 0],
[0, 0, 0, 0],
[2, 0, 0, 2],
[0, 0, 0, 0], ]

我想创建一个新的,只改变B不为0并且与a不同的值,结果将是:

c = [
[1, 1, 1, 1],
[1, 0, 0, 1],
[2, 0, 0, 2],
[1, 1, 1, 1], ]

我该怎么做?

您可以使用布尔条件进行赋值:

a[b != 0] = b[b != 0]
a
array([[1, 1, 1, 1],
[1, 0, 0, 1],
[2, 0, 0, 2],
[1, 1, 1, 1]])

我觉得很容易解析:

>>> np.where(b,b,a)
array([[1, 1, 1, 1],
[1, 0, 0, 1],
[2, 0, 0, 2],
[1, 1, 1, 1]])

根据第一个参数是否为零,从第三个或第二个参数中选择每个值。

不需要numpy。下面是一个可以逐行读取的解决方案:

a = [
[1, 1, 1, 1],
[1, 0, 0, 1],
[1, 0, 0, 1],
[1, 1, 1, 1], ]
b = [
[0, 1, 1, 0],
[0, 0, 0, 0],
[2, 0, 0, 2],
[0, 0, 0, 0], ]
c = a[:]
#I would like to create a new one, only changing the values where B is not 0 and is different than A. The result would be:
for lineindex,line in enumerate(a):
for index,x in enumerate(line):
if x != b[lineindex][index] and b[lineindex][index] != 0:
c[lineindex][index] = b[lineindex][index]
print(c)

最新更新