【问题标题】:Python Pandas: Convert nested dictionary to dataframePython Pandas:将嵌套字典转换为数据框
【发布时间】:2015-10-06 06:06:41
【问题描述】:

我有一个这样的字典:

{1 : {'tp': 26, 'fp': 112},
2 : {'tp': 26, 'fp': 91},
3 : {'tp': 23, 'fp': 74}}

我想转换成这样的数据框:

t tp fp
1 26  112
2 26  91
3 23  74

有人知道吗?

【问题讨论】:

    标签: python dictionary pandas nested


    【解决方案1】:

    尝试DataFrame.from_dict() 并使用关键字参数orient 作为'index' -

    例子-

    In [20]: d = {1 : {'tp': 26, 'fp': 112},
       ....: 2 : {'tp': 26, 'fp': 91},
       ....: 3 : {'tp': 23, 'fp': 74}}
    
    In [24]: df =pd.DataFrame.from_dict(d,orient='index')
    
    In [25]: df
    Out[25]:
       tp   fp
    1  26  112
    2  26   91
    3  23   74
    

    如果您还想为 index 列设置列名,请使用 - df.index.name ,示例 -

    In [30]: df.index.name = 't'
    
    In [31]: df
    Out[31]:
       tp   fp
    t
    1  26  112
    2  26   91
    3  23   74
    

    【讨论】:

      【解决方案2】:

      我只是想指出(因为这是从嵌套字典转换为 pandas 数据帧的最佳结果之一)还有其他嵌套字典的方法也可以转换为数据帧(例如通过列嵌套)。

      例如以下嵌套字典

      patients = {"Name":{"0":"John","1":"Nick","2":"Ali","3":"Joseph"},
                  "Gender":{"0":"Male","1":"Male","2":"Female","3":"Male"},
                  "Nationality":{"0":"UK","1":"French","2":"USA","3":"Brazil"},
                  "Age" :{"0":10,"1":25,"2":35,"3":29}}
      

      可以使用 orient='columns' 转换为 pandas 数据框

      df_patients = pd.DataFrame.from_dict(patients, orient='columns')

      【讨论】:

        猜你喜欢
        • 2021-11-28
        • 2022-01-07
        • 2021-12-21
        • 2021-06-30
        • 2018-06-03
        • 1970-01-01
        • 2021-08-06
        • 2017-03-24
        • 2014-05-10
        相关资源
        最近更新 更多