将字典转换为两列熊猫数据帧



我在python中有一个名为word_counts的字典,它由关键字和值组成,这些关键字和值表示它们在给定文本中出现的频率:

word_counts = {'the':2, 'cat':2, 'sat':1, 'with':1, 'other':1}

我现在需要将其制作成具有两列的熊猫数据帧:名为"word"的列表示单词,名为"count"的列表示频率。

>>> import pandas as pd
>>> pd.DataFrame(list(word_counts.items()), columns=['word', 'count'])
word  count
0    the      2
1    cat      2
2    sat      1
3   with      1
4  other      1

您可以从字典创建数据帧:

df=pd.DataFrame({"word":list(word_counts.keys()) , "count": list(word_counts.values())})

您可以使用pd.DataFrame中的.from_dict附属物

pd.DataFrame.from_dict(word_counts, orient="index", columns=["Count"]).rename_axis(
"Word", axis=1
)
Word   Count
the        2
cat        2
sat        1
with       1
other      1

最新更新