我有一个来自json的字典,其中我通过循环汇总通过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
我在熊猫中尝试了几种不同的选择,但无法获得理想的结果。
如果每个人都有一个非空值,请使用带有过滤功能的嵌套字典理解:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句