【问题标题】:How can I multiply items in two arrays if there are zeros in python?如果python中有零,如何将两个数组中的项目相乘?
【发布时间】:2021-08-06 12:50:02
【问题描述】:

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

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

【问题讨论】:

  • 你需要添加更多细节,你没有给出任何你遵循的“规则”来达到你的预期操作;例如你如何确定第三个数组中的最后一个元素是0.12*0.08
  • 哦,是的。实际上我想忽略数组内的零,并对两个数组进行逐行乘法。谢谢你的建议!

标签: python arrays list numpy multiplication


【解决方案1】:

只需将两个数组上的零值替换为 1,然后将 a*baxis=1keepdims=True 传递给 np.prod

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

【讨论】:

  • 也非常感谢您的帮助!这确实是更智能的方式。我以前没有这个想法。我一定会用这个方法。
【解决方案2】:

考虑以下策略:

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

【讨论】:

  • 预期输出是一个二维数组。
  • 哦,是的,我之前尝试过使用 np.hstack,但我不知道下一步如何工作。感谢您的帮助让我知道!对我也很有用!
【解决方案3】:

你可以这样做

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

【讨论】:

  • 非常感谢!这真的有效!我现在在 python 中学到了很多东西。
猜你喜欢
  • 2018-12-17
  • 1970-01-01
  • 1970-01-01
  • 2013-12-19
  • 2021-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多