无法将我的字典转换为数据框

时间:2019-09-23 12:14:24

标签: python pandas dictionary

我有这样的字典

{'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'),但它给了我其他东西:

enter image description here

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

任何建议将不胜感激。

3 个答案:

答案 0 :(得分:1)

可以直接在字典中创建pd.Series,然后使用.to_frame()方法将pd.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

答案 1 :(得分:1)

这取决于您要在Dataframe中使用哪种结构。

如果要将dict中的键显示为行值,请使用:

-> pd.DataFrame(pd.Series(d))。reset_index()

如果要在字典中将键显示为列,请执行以下步骤:

  1. 首先在“列表”中使用字典,如下所示:

    d = [ { 'community_0':31, 'community_1':29 'community_2':15 } ]

  2. 然后使用-> pd.DataFrame.from_dict(d)

答案 2 :(得分:0)

pd.DataFrame([d])会成功。