在Datafram中展开嵌套dict

2024-10-03 13:23:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在输出到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'}}}

到目前为止,我已经尝试过:

^{pr2}$

然后分道扬镳:

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

所以我需要熔化/取消堆叠/透视/展开/其他操作_word数据帧中的嵌套字典。在

我看了这篇文章以寻求指导,但无法将其应用于我自己: Expand pandas dataframe column of dict into dataframe columns


Tags: theanswer字典onequestionpartthproof
1条回答
网友
1楼 · 发布于 2024-10-03 13:23:37

以下是一个潜在的解决方案:

1)创建具有方向“index”的初始DataFrame

df = pd.DataFrame.from_dict(review, orient='index')

2)使用^{}^{}和{a3}创建最终DataFrame的形状

^{pr2}$

3)通过传递给DataFrame构造函数并使用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

相关问题 更多 >