Pandas dataframe from nested dictionary

前端 未结 2 915
再見小時候
再見小時候 2021-01-06 07:21

My dictionary looks like this:

{\'x\': {\'b\': 10, \'c\': 20}, \'y\': {\'b\': \'33\', \'c\': 44}}

I want to get a dataframe that looks like

相关标签:
2条回答
  • 2021-01-06 07:48

    You can use a list comprehension to reorder your dict into a list of tuples where each tuple is a row and then you can sort your dataframe

    import pandas as pd
    
    d = {'x': {'b': 10, 'c': 20}, 'y': {'b': '33', 'c': 44}}
    
    df = pd.DataFrame([(k,k1,v1) for k,v in d.items() for k1,v1 in v.items()], columns = ['Col1','Col2','Val'])
    print df.sort(['Col1','Col2','Val'], ascending=[1,1,1])
    
      Col1 Col2 Val
    3    x    b  10
    2    x    c  20
    1    y    b  33
    0    y    c  44
    
    0 讨论(0)
  • 2021-01-06 07:56

    first create the df using from_dict, then call stack and reset_index to get the shape you desire, you then need to rename the cols, sort and reset the index:

    In [83]:
    d={'x': {'b': 10, 'c': 20}, 'y': {'b': '33', 'c': 44}}
    df = pd.DataFrame.from_dict(d, orient='index').stack().reset_index()
    df.columns = ['col1', 'col2', 'val']
    df.sort_values(['col1', 'col2'], inplace=True)
    df.reset_index(drop=True, inplace=True)
    df
    
    Out[83]:
      col1 col2 val
    0    x    b  10
    1    x    c  20
    2    y    b  33
    3    y    c  44
    
    0 讨论(0)
提交回复
热议问题