PParker
PParker

Reputation: 1511

Convert dictionary with list into pandas dataframe

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:

  1. industryPredictions
  2. The list given in paymentmethods

Upvotes: 1

Views: 129

Answers (1)

ThePyGuy
ThePyGuy

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

Related Questions