首页 > 解决方案 > 无法将我的字典转换为数据框

问题描述

我有一本这样的字典

{'community_0': 30,
'community_1': 29,
'community_2': 15,
'community_3': 16,
'community_4': 123,
'community_5': 9,
'community_6': 36,
'community_7': 71,
'community_8': 95,
'community_9': 21}

我想将其转换为熊猫数据框。我试过pd.DataFrame.from_dict(dict, orient='index')了,但它给了我别的东西:

在此处输入图像描述

我参考了这篇文章Convert Python dict into a dataframe 但它并没有太大帮助。

任何建议,将不胜感激。

标签: pythonpandasdictionary

解决方案


可以直接从字典中创建 a pd.Series,然后使用该.to_frame()方法将 apd.Series转换为单列 DataFrame:

import pandas as pd

d = {'community_0': 30,
'community_1': 29,
'community_2': 15,
'community_3': 16,
'community_4': 123,
'community_5': 9,
'community_6': 36,
'community_7': 71,
'community_8': 95,
'community_9': 21}

pd.Series(d).to_frame()

返回:

            0
community_0 30
community_1 29
community_2 15
community_3 16
community_4 123
community_5 9
community_6 36
community_7 71
community_8 95
community_9 21

推荐阅读