python - Set value in 2D Numpy array based on row sum
问题描述
Is this possible to accomplish with Numpy and with good performance?
Initial 2D array:
array([[0, 1, 1, 1, 1, 0],
[0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 1]])
If the sum of each row is less than 4, set the last item in each row to 1:
array([[0, 1, 1, 1, 1, 0],
[0, 0, 1, 0, 0, 1],
[1, 0, 0, 0, 0, 1]])
Divide each item in each row with the sum of each row and get this result:
array([[0, 0.25, 0.25, 0.25, 0.25, 0],
[0, 0, 0.5, 0, 0, 0.5],
[0.5, 0, 0, 0, 0, 0.5]])
解决方案
:numpy.where
在此处查找与您的条件匹配的行也很有用
import numpy as np
a = np.array([[0, 1, 1, 1, 1, 0],
[0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 1]])
a[np.sum(a,axis=1) < 4, -1] = 1
a = a/a.sum(axis=1)[:,None]
print(a)
# Output
# [[0. 0.25 0.25 0.25 0.25 0. ]
# [0. 0. 0.5 0. 0. 0.5 ]
# [0.5 0. 0. 0. 0. 0.5 ]]
PS:在@tel 建议后编辑:)
推荐阅读
- load-testing - Locust 如何为负载测试提供一段时间内的状态?
- java - 如何处理 Java ThreadPoolExecutor 中的线程挂起?
- php - "Username/Email is already registered" shows up even if i didn't registered yet
- c# - Visual Studio C# Web 应用程序 - 如何获取指针的不安全关键字
- amazon-web-services - 无法将 Internet 与私有子网中的 EC2 实例连接
- docker - Docker Compose 作为 CI 管道
- json - Morris.js setData 不起作用,除非我这样做
- html - 当鼠标光标离开导航父项时子菜单消失
- git - 如何让 git 跟踪新文件,而不仅仅是现有文件?
- python - 如何通过编辑以前的数据在烧瓶上流式传输数据?