首页 > 解决方案 > 如果python中有零,如何将两个数组中的项目相乘?

问题描述

我在python中有两个数组。

对于一个,它看起来像

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]])

我怎样才能做到这一点?我真的可以使用你的帮助。

标签: pythonarrayslistnumpymultiplication

解决方案


只需将两个数组上的零值替换为 1,然后传递a*bnp.prodwithaxis=1keepdims=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]])

推荐阅读