【问题标题】:Faster Python implementation from bag of words data frame to array从词袋数据帧到数组的更快 Python 实现
【发布时间】:2018-08-05 04:42:04
【问题描述】:

我有一个 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

我需要一种快速 方法来返回一个词袋数组矩阵。假设我的词汇长度是 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 以实现快速实现。我怎样才能做到这一点?谢谢

【问题讨论】:

标签: python performance pandas numpy apply


【解决方案1】:

这似乎解决了你的问题:

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

【讨论】:

    【解决方案2】:

    我觉得你需要

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

    然后我们转换成tuple ot list

    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
    

    【讨论】:

      【解决方案3】:

      散列应该使它更快 - 您可以使用集合库及其默认字典作为启动器,然后从每个字典输出构建一个向量。

      word_frequencies = collections.defaultdict(int) 言归正传: 如果单词不在字典中: 字典[单词] = len(字典) word_frequencies[dictionary[word]] += 1

      最后你需要的是 word_frequencies.items()

      【讨论】:

        猜你喜欢
        • 2019-03-15
        • 2018-07-26
        • 1970-01-01
        • 2018-03-11
        • 1970-01-01
        • 2020-06-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多