3

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},
}}
Sa K
  • 31
  • 2

1 Answers1

1

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()}
ansev
  • 30,322
  • 5
  • 17
  • 31