Python 将嵌套的dict从json转换为以值为列的数据帧

Python 将嵌套的dict从json转换为以值为列的数据帧,python,json,pandas,Python,Json,Pandas,我有一个来自json的dict,其中我通过一个循环为通过API回答的每个人汇总调查结果,并希望将其转换为一个数据框架,该数据框架使用“title”值作为列,然后将一个人的所有答案放在一行中 这就是参与调查的一个人的原始结果: {'0': {'title': 'What department do you work?', 'results': {'0': '', '1': '', '2': '', '3': 'Unit D'}}, '1': {'title': 'I can f

我有一个来自json的dict,其中我通过一个循环为通过API回答的每个人汇总调查结果,并希望将其转换为一个数据框架,该数据框架使用“title”值作为列,然后将一个人的所有答案放在一行中

这就是参与调查的一个人的原始结果:

 {'0': {'title': 'What department do you work?',
    'results': {'0': '', '1': '', '2': '', '3': 'Unit D'}}, 
    '1': {'title': 'I can focus on clear targets?',
    'results': {'0': 'Yes', '1': '', '2': ''}}
这就是数据帧的外观:

Result ID  |  What department do you work in? | I can focus on clear targets
    1      |  Unit D                          | Yes 

我在pandas中尝试了几个不同的选项,但没有得到想要的结果。

如果每人有一个非空值,请使用嵌套字典理解和筛选:

d =  {'0': {'title': 'What department do you work?',
    'results': {'0': '', '1': '', '2': '', '3': 'Unit D'}}, 
    '1': {'title': 'I can focus on clear targets?',
    'results': {'0': 'Yes', '1': '', '2': ''}}}

df = pd.DataFrame({v['title']: [v1 for k1, v1 in v['results'].items() if v1] 
                   for k, v in d.items()})
print (df)
  What department do you work? I can focus on clear targets?
0                       Unit D                           Yes
如果可能,多个值:

d =  {'0': {'title': 'What department do you work?',
    'results': {'0': '', '1': '', '2': '', '3': 'Unit D'}}, 
    '1': {'title': 'I can focus on clear targets?',
    'results': {'0': 'Yes', '1': 'No', '2': ''}}}


df = pd.DataFrame({v['title']: pd.Series([v1 for k1, v1 in v['results'].items() if v1])
                   for k, v in d.items()})
print (df)
  What department do you work? I can focus on clear targets?
0                       Unit D                           Yes
1                          NaN                            No

谢谢你快速而深刻的回答。第二个选项对我来说很有魅力!看到这一幕,我真的需要复习一下我的熊猫知识!再次感谢。