【问题标题】:Nested dictionary to dataframe preserving the dictionary key as column instead of index嵌套字典到数据框,将字典键保留为列而不是索引
【发布时间】:2018-11-19 02:23:21
【问题描述】:

字典的格式如图所示

{1:{'3450':0.235, '4380':0.47823},11:{'0430':0.128912,'0986':0.6267},14:{'8060':0.218912,'1234':0.6238}}

我可以创建一个如图所示的数据框

   chapter name  value
 0    1    3450  0.235
 1    1    4380  0.478
 2    11   0430  0.128912
 3    11   0986  0.6267
 4    14   8060  0.218912
 5    14   1234  0.6238

我尝试转换为数据框,但我将章节作为索引,我需要将其作为列。

【问题讨论】:

    标签: python pandas dictionary dataframe


    【解决方案1】:

    使用stack

    df=pd.DataFrame(d).stack().reset_index()
    df.columns=['name','chapter','value']
    df
    Out[113]: 
       name  chapter     value
    0  0430       11  0.128912
    1  0986       11  0.626700
    2  1234       14  0.623800
    3  3450        1  0.235000
    4  4380        1  0.478230
    5  8060       14  0.218912
    

    【讨论】:

    • 根据问题需要对列重新排序:df = df[['chapter','name','value']]
    【解决方案2】:

    或手动:

    df=pd.DataFrame(d).reset_index()
    df['value']=df.pop(1).fillna(df.pop(11)).fillna(df.pop(14))
    df['chapter']=sorted(list(d.keys())*2)
    df.columns=['name','value','chapter']
    

    那么现在:

    print(df)
    

    是:

       name     value  chapter
    0  0430  0.128912        1
    1  0986  0.626700        1
    2  1234  0.623800       11
    3  3450  0.235000       11
    4  4380  0.478230       14
    5  8060  0.218912       14
    

    重新排序列:

    df=df[['chapter','name','value']]
    

    【讨论】:

    • 根据问题需要对列重新排序:df = df[['chapter','name','value']]
    猜你喜欢
    • 2014-09-19
    • 2022-07-01
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 2018-06-03
    • 2020-07-31
    • 2014-03-29
    • 2017-11-27
    相关资源
    最近更新 更多