【发布时间】:2019-09-03 03:41:56
【问题描述】:
我想在将嵌套字典输出到 csv 之前重新格式化它。 我的嵌套字典:
review = {'Q1': {'Question': 'question wording','Answer': {'Part 1': 'Answer part one', 'Part 2': 'Answer part 2'} ,'Proof': {'Part 1': 'The proof part one', 'Part 2': 'The proof part 2'}},
'Q2': {'Question': 'question wording','Answer': {'Part 1': 'Answer part one', 'Part 2': 'Answer part 2'} ,'Proof': {'Part 1': 'The proof part one', 'Part 2': 'The proof part 2'}}}
到目前为止我已经尝试过:
my_df = pd.DataFrame(review)
my_df = my_df.unstack()
然后分道扬镳:
Q1 Answer {'Part 1': 'Answer part one', 'Part 2': 'Answe...
Proof {'Part 1': 'The proof part one', 'Part 2': 'Th...
Question question wording
Q2 Answer {'Part 1': 'Answer part one', 'Part 2': 'Answe...
Proof {'Part 1': 'The proof part one', 'Part 2': 'Th...
Question question wording
但我希望它最终看起来像这样:
Index Question Answer Proof
Q1 question one wording Answer part 1 Proof part 1
Q1 question one wording Answer part 2 Proof part 2
Q2 question two wording Answer part 1 Proof part 1
Q2 question two wording Answer part 2 Proof part 2
所以我需要将 Dataframe 中的嵌套字典融化/unstack/pivot/expand/other_manipulation_word。
我已查看此指南以获取指导,但无法将其应用于我自己的: Expand pandas dataframe column of dict into dataframe columns
【问题讨论】:
-
我不确定如何获得您想要的确切布局,但 df.reset_index 会在索引列上达到预期的效果。