【问题标题】:Expand nested dict within Dataframe在 Dataframe 中展开嵌套的 dict
【发布时间】: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 会在索引列上达到预期的效果。

标签: python pandas dataframe


【解决方案1】:

这是一种可能的解决方案:

1) 使用 orient 'index' 创建初始 DataFrame

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

2) 使用Index.repeatSeries.str.lenDataFrame.loc 创建最终DataFrame 的形状

df_new = df.loc[df.index.repeat(df.Answer.str.len())]

3) 通过传递给DataFrame 构造函数并使用stack 值来修复“答案”和“证明”列

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

【讨论】:

  • to_list() 是 Pandas 的函数吗?我在这里看不到它:pandas.pydata.org/pandas-docs/stable/reference/api/…,我收到一个错误:AttributeError: 'Series' object has no attribute 'to_list'
  • 您可能使用的是旧版本的熊猫...?试试不带下划线的tolist()
  • 这很好用,但我很惊讶没有一种方法可以不强制它。我可以通过一个问题得到正确的格式,即 Q1,做: df = pd.DataFrame.from_dict(review['Q1']) print(df.T.unstack())
猜你喜欢
  • 1970-01-01
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-30
  • 2018-11-01
  • 1970-01-01
相关资源
最近更新 更多