【问题标题】:Update a DataFrame based on Counter values根据 Counter 值更新 DataFrame
【发布时间】:2022-01-23 15:13:50
【问题描述】:

我有一个语料库data,存储为字符串列表。

根据这些数据,我有以下变量:

vocab_dict = Counter()
for text in data_words:
    temp_count = Counter(text)
    vocab_dict.update(temp_count)
vocab=list(sorted(vocab_dict.keys()))

现在,我想创建一个 pandas DataFrame,如果 vocab_dict 中的值大于 3,则每列代表来自 vocab 的一个词。

为此,我有以下代码:

def get_occurrence_df(data):
    vocab_words = [word for word in vocab if vocab_dict[word] > 3]
    occurrence_df = pd.DataFrame(0, index = np.arange(len(data)), columns = vocab_words)
    for i, text in enumerate(data):
        text_count = Counter(text)
        for word in text_count.keys():
            occurrence_df.loc[i, word] = text_count[word]
    return occurrence_df

但是,运行函数get_occurrence_df() 需要很长时间。有没有办法更快地获得相同的df?

【问题讨论】:

    标签: python pandas dataframe counter


    【解决方案1】:

    这应该会更快一些,它不是函数形式,但应该可以直接重构:

    from collections import Counter
    import pandas as pd
    
    data_words = [["abc", "def", "abc"], ["xyz", "xyz", "xyz", "def"]]
    
    # create a list of dictionaries with counts
    temp_list = [
        {k: v for k, v in Counter(words).items() if v >= 2}
        for words in data_words
    ]
    
    occurrence_df = pd.DataFrame(temp_list).fillna(0)
    

    请注意,最好立即过滤掉常用词,因为会有很多不常用词,并且用不会在下游使用的对象阻塞内存是不好的。

    【讨论】:

      猜你喜欢
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-18
      • 2022-07-05
      • 2018-03-16
      • 1970-01-01
      • 2012-10-15
      相关资源
      最近更新 更多