如果 python 中有零,我如何将两个数组中的项相乘?

How can I multiply items in two arrays if there are zeros in python?

我在 python 中有两个数组。

对于a来说,它看起来像

array([[0.  , 0.08],
       [0.12, 0.  ],
       [0.12, 0.08]])

对于b来说,它看起来像

array([[0.88, 0.  ],
       [0.  , 0.92],
       [0.  , 0.  ]])

我想像下面这样对这两个数组进行乘法运算:

array([[0.08*0.88],     ### 1st row of a multiplies 1st row of b without zeros
       [0.12*0.92],     ### 2nd row of a multiplies 2nd row of b without zeros
       [0.12*0.08]])    ### multiplies o.12 and 0.08 together in 3rd row of a without zeros in 3rd row of b

而最终想要的结果是:

array([[0.0704],
       [0.1104],
       [0.0096]])

我怎样才能做到这一点?我真的需要你的帮助。

你可以这样做

# First concatenate both the arrays
temp = np.concatenate((arr1, arr2), axis=1)
'''
the result will be like this
array([[0.  , 0.08, 0.88, 0.  ],
       [0.12, 0.  , 0.  , 0.92],
       [0.12, 0.08, 0.  , 0.  ]])
'''
# Sort the arrays
temp.sort()
'''
result: array([[0.  , 0.  , 0.08, 0.88],
       [0.  , 0.  , 0.12, 0.92],
       [0.  , 0.  , 0.08, 0.12]])
'''
res = temp[:, -1] * temp[:, -2]
'''
result: array([0.0704, 0.1104, 0.0096])
'''

只需将两个数组中的零值替换为 1,然后将 a*b 传递给 np.prodaxis=1,以及 keepdims=True:

>>> a[a==0] = 1
>>> b[b==0] = 1
>>> np.prod(a*b, axis=1, keepdims=True)
#output:
array([[0.0704],
       [0.1104],
       [0.0096]])

考虑以下策略:

a = np.array([[0.  , 0.08],
   [0.12, 0.  ],
   [0.12, 0.08]])

b = np.array([[0.88, 0.  ],
   [0.  , 0.92],
   [0.  , 0.  ]])

c = np.hstack([a, b]) # stick a and b together along axis 1
d = np.where(c == 0, 1, c) # turn the 0s into 1s
result = np.prod(d, axis=1) # calculate the production along axis 1
# array([0.0704, 0.1104, 0.0096])