【发布时间】:2018-05-26 22:28:50
【问题描述】:
我正在寻找一种 numpy 解决方案,用不同的一维计数器数组(在下面的例子)。
我尝试了以下方法:
import numpy as np
cnt = np.array([1, 3, 2, 4]) # cnt array: how much elements per column are 1
a = np.zeros((5, 4)) # array that must be filled with 1s per column
for i in range(4): # for each column
a[:cnt[i], i] = 1 # all elements from top to cnt value are filled
print(a)
并给出所需的输出:
[[1. 1. 1. 1.]
[0. 1. 1. 1.]
[0. 1. 0. 1.]
[0. 0. 0. 1.]
[0. 0. 0. 0.]]
有没有一种更简单(和更快)的方法可以使用 numpy 例程来执行此操作,而无需每列循环?
a = np.full((5, 4), 1, cnt)
类似上面的东西会很好,但不起作用。
感谢您的宝贵时间!
【问题讨论】:
标签: python arrays numpy autofill