Python 展开Dataframe中的嵌套dict

Python 展开Dataframe中的嵌套dict,python,pandas,dataframe,Python,Pandas,Dataframe,我想在将嵌套字典输出到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': 'qu

我想在将嵌套字典输出到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
因此,我需要在数据框中融化/取消堆叠/透视/展开/其他\u操作\u单词嵌套字典

我已将此作为指导,但无法将其应用于我自己的:
这里有一个潜在的解决方案:

1) 使用orient“index”创建初始数据帧

df = pd.DataFrame.from_dict(review, orient='index')
2) 使用和创建最终数据帧的形状

3) 通过传递到
DataFrame
constructor并使用
stack
值来修复“Answer”和“Proof”列

df_new['Answer'] = pd.DataFrame(df.Answer.tolist()).stack().values
df_new['Proof'] = pd.DataFrame(df.Proof.tolist()).stack().values
print(df_new)

            Question           Answer               Proof
Q1  question wording  Answer part one  The proof part one
Q1  question wording    Answer part 2    The proof part 2
Q2  question wording  Answer part one  The proof part one
Q2  question wording    Answer part 2    The proof part 2

我不确定如何获得您想要的确切布局,但df.reset\u index将在索引列上实现所需的效果。to\u list()是Pandas的函数吗?我在这里看不到它:我得到一个错误:AttributeError:'Series'对象没有属性'to_list'看到你可能正在使用一个旧版本的pandas。。。?尝试不带下划线的
tolist()
?这很有效,但我很惊讶没有一个方法不强制它。我只需要一个问题就可以得到正确的格式,即Q1,doing:df=pd.DataFrame.from_dict(review['Q1'])print(df.T.unstack())
df_new['Answer'] = pd.DataFrame(df.Answer.tolist()).stack().values
df_new['Proof'] = pd.DataFrame(df.Proof.tolist()).stack().values
print(df_new)

            Question           Answer               Proof
Q1  question wording  Answer part one  The proof part one
Q1  question wording    Answer part 2    The proof part 2
Q2  question wording  Answer part one  The proof part one
Q2  question wording    Answer part 2    The proof part 2