我尝试通过词汇来计算单词频率:
vocabulary = {}
for word in lemmatizer_results:
if word in vocabulary:
vocabulary[word] += 1
else:
vocabulary[word] = 1
在此之后,我尝试通过以下方式将结果转换为 DataFrame:
df = pd.DataFrame.from_dict(vocabulary, orient='index', columns=['word', 'frequency'])
如果字典的结构如下:
vocabulary = {'word1': [3],
'word2': [34]}
但我有这样的结构:
vocabulary = {'three': 1622,
'elephant': 66,
'power': 1070,
'story': 667,
'b': 65,
'paterson': 1,}
你能帮我根据这些数据创建 DF 吗?谢谢!
最佳答案
你们很接近。使用orient='index'
,字典键转换为数据帧索引,而值转换为数据。因此您可以重命名索引,然后重置它。
df = pd.DataFrame.from_dict(vocabulary, orient='index', columns=['frequency'])\
.rename_axis('word').reset_index()
print(df)
word frequency
0 three 1622
1 elephant 66
2 power 1070
3 story 667
4 b 65
5 paterson 1
关于python - 如何使用非标准分隔符从词汇创建 DF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54409680/