python - 如果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]])
我怎样才能做到这一点?我真的可以使用你的帮助。
解决方案
只需将两个数组上的零值替换为 1,然后传递a*b
给np.prod
withaxis=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]])
推荐阅读
- php - WampServer 3.2.3 无法访问局域网,
- python - .env 从 CLI 运行时未加载,但从 VSCode 运行时
- go - 如何使用 pgx 记录查询?
- javascript - 使用 XMLHttpRequest,我正在尝试建立一个旁边有评论的博客
- python - 来自 scipy 的 jarque_bera 计算
- android - KeyEvents在android中的文本之后没有占用空间
- c# - 使用自定义方法结合 Where 和 OrderByDescending
- sql - 这是一个 Sql-Server 查询,如何在 Postgresql 中执行?
- java - Quarkus 和 Redis
- java - Why Selection event not triggered when selection is done using keyboard?