Search code examples
pythonpandas

Convert dictionary of dictionaries to pandas dataframe


I have a dictionary like so:

d = {
    '2020-07-27': {'distinct_ntwrk_cd': 127, 'distinct_inv_type_cd': 44, 'distinct_syscode': 679},
    '2020-07-28': {'distinct_ntwrk_cd': 124, 'distinct_inv_type_cd': 43, 'distinct_syscode': 678}
}

And would like to convert it to a pandas dataframe like so:

Date distinct_ntwrk_cd distinct_inv_type_cd distinct_syscode
2020-07-27 127 44 679
2020-07-28 124 43 678

Doesn't matter to me if the date is the index or not. What is the easiest way to do this?


Solution

  • With date being index, you can just do:

    df = pd.DataFrame(d).T
    

    You can further try rename the index, and chain with reset_index to make date a normal column:

    pd.DataFrame(d).T.rename_axis('Date').reset_index()
    

    Output:

             Date  distinct_ntwrk_cd  distinct_inv_type_cd  distinct_syscode
    0  2020-07-27                127                    44               679
    1  2020-07-28                124                    43               678