【发布时间】: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