python - 如何使用非标准分隔符从词汇创建 DF?

标签 python pandas dictionary dataframe

我尝试通过词汇来计算单词频率:

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/

相关文章:

python - 有没有更快的方法来添加两个二维 numpy 数组

python Pandas : how to find rows in one dataframe but not in another?

python - 使用条件总和的结果创建 Pandas DataFrame 列

bash - 如何检查字典是否包含bash中的键?

arrays - iOS - 字典中的顺序问题

java - 实体中带有复合键的 Map<String, Entity>

python - 如何在Python中的线程中增加类字段?

python - 创建无限循环生成器的巧妙方法?

Python - 对每一行使用 rsplit 将字符串转换为表格

python - pandas 中的广义系列拆分(一对多映射)