Pandas dataframe to nested dictionary with a name space as None

Viewed 68

I have a pd dataframe like this and need to convert into dictionary with a None namespace and dataframe as nested?

pandas dataframe

data = {None: {
    'Periods': {None: 8759},
    'Years': {None: 20},
    'Scenarios': {None: 1},
    'Scenario_Weight': {1: 1},
}}
1 Answers

Try DataFrame.pivot + DataFrame.to_dict

data = {None : df.pivot(index='Index', columns='Key', values='Value').to_dict()}

Or:

data = {None : df.pivot(*df).to_dict()}

If necessary replace blanks:

data = {None : df.replace(r'^\s*$', None, regex=True).pivot(*df).to_dict()}
Related