我有一本 Python 字典
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}
我想展平字典以便将其转换为 pandas dataframe 类似于:
kontonummer industryPredictions.Supermarket industryPredictions.Cars paymentmethods pricesAmount pricesMean pricesQ25
0 None 0.006795 0.011132 ['Klarna Sofort...] 2721 30.79 12.99
我知道如何将 dict 转换为 dataframe。我的问题是将字典转换为所需的结构。
如您所见,有两个挑战:
industryPredictions
paymentmethods
中给出的列表答案 0 :(得分:2)
只需使用 pd.json_normalize
,然后传递您拥有的字典
>>> 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
即使列表中有多个这样的字典,它也能工作:pd.json_normalize([result_dict, result_dict])