Reputation: 1511
I have a Python dictionary
result_dict = { 'kontonummer': None,
'industryPredictions': {'Supermarket': 0.006795256825841207,
'Cars': 0.01113155396585519},
'paymentmethods': ['Klarna SofortUeberweisung',
'Klarna Ratenkauf.',
'Ueberweisung'],
'pricesAmount': 2721,
'pricesMean': 30.796045571481077,
'pricesQ25': 12.99}
I want to flatten the dictionary in order to convert it to a pandas dataframe similar to this:
kontonummer industryPredictions.Supermarket industryPredictions.Cars paymentmethods pricesAmount pricesMean pricesQ25
0 None 0.006795 0.011132 ['Klarna Sofort...] 2721 30.79 12.99
I know how to convert a dict into a dataframe. My problem is to convert the dictionary into the desired structure.
As you can see, there are 2 challenges:
industryPredictions
paymentmethods
Upvotes: 1
Views: 129
Reputation: 18426
Just use the pd.json_normalize
, and pass the dictionary you have
>>> pd.json_normalize(result_dict)
kontonummer paymentmethods pricesAmount pricesMean pricesQ25 industryPredictions.Supermarket industryPredictions.Cars
0 None [Klarna SofortUeberweisung, Klarna Ratenkauf., Ueberweisung] 2721 30.796046 12.99 0.006795 0.011132
It will work even if you have multiple such dictionaries in a list like : pd.json_normalize([result_dict, result_dict])
Upvotes: 2