Python:从有序列表[value, repeatedNumber]制作numpy数组



列表[[value, repeatedNo], ...]转换为一维数字数组的最快方法是什么?

到目前为止,我有这个:

import numpy as np    
bln = np.zeros(15)
counted_data = [[0,10],[1,2],[0,3]]
vrIndex =0
for vr in counted_data:
    if vr[0] == 0:
        vrIndex += vr[1]
    else:
        bln[vrIndex:vrIndex+vr[1]] =1
        vrIndex += vr[1]
print bln

哪些打印:

[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  1.  0.  0.  0.]

问题是bln是 500,000 个元素,我必须这样做 1000 次,这很慢。

我也尝试过:

 bln = []
 for vr in counted_data:
     bln += list(Counter(dict([vr])).elements())

最简单(也可能是最快的)方法是将数据传递给np.repeat

>>> np.repeat([0, 1, 0], repeats=[10, 2, 3])
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0])

如果您的数据以counted_data的形式作为列表列表:

np.repeat(*zip(*counted_data))

最新更新