从单词数据框到数组的更快的Python实现

时间:2018-02-25 17:33:06

标签: python performance pandas numpy apply

我有一个pandas数据框,它定义了我的一系列单词索引,并且计算如下。

id      word_count  word_idx
15213   1           1192
15213   1           1215
15213   1           1674
15213   1           80
15213   1           179
307     2           103
307     1           80
307     3           1976

我需要一个 fast 方式来返回一个单词数组矩阵。假设我的词汇长度为2000:VOCAB_LEN = 2000

我目前的解决方案是太慢了。但这是:

功能

def to_bow_array(word_idx_list, word_count_list):
    zeros = np.zeros(VOCAB_LEN, dtype = np.uint8)
    zeros[np.array(word_idx_list)] = np.array(word_count_list)
    return zeros

分组并应用功能

df.groupby('id').apply(lambda row: to_bow_array(list(row['word_idx']),
                                               list(row['word_count'])))

这将返回我的预期输出。对于每一行,类似于 array([0, 0, 1, ..., 0, 2, 0], dtype=uint8)

我需要更快的实施。我知道快速实现应该避免使用apply。我怎样才能做到这一点?感谢

2 个答案:

答案 0 :(得分:2)

我认为你需要

s=df.set_index(['id','word_idx'])['word_count'].unstack(fill_value=0).reindex(columns=np.arange(2000),fill_value=0)

然后我们转换为元组列表

s.apply(tuple,1)
Out[342]: 
id
307      (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...
15213    (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...
dtype: object

答案 1 :(得分:0)

这似乎可以解决您的问题:

df.groupby(['id', 'word_idx']).sum().unstack()