【问题标题】:Merge dataframes in a dictionary合并字典中的数据框
【发布时间】:2015-07-25 20:55:16
【问题描述】:

假设我有一个数据框字典:

  {'df1': name         color    type
          Apple        Yellow   Fruit,
   'df2': name         color    type
          Banana       Red      Fruit,
   'df3': name         color    type
          Chocolate    Brown    Sweet
    ......}

我想像这样将它们合并为一个:

  name         color    type
  Apple        Red      Fruit 
  Banana       Yellow   Fruit
  Chocolate    Brown    Sweet

我可以手动操作如下:

  merge1=pd.merge('df1','df2')
  merge2=pd.merge('merge1','df3')
  ...

但是有没有办法自动压缩字典并合并? 任何帮助表示赞赏。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以直接传递dict并将values属性访问到concat

    In [233]:
    
    d
    Out[233]:
    {'df1':     name         color    type
     0  Apple        Yellow   Fruit, 'df2':     name         color    type
     0  Banana       Red      Fruit, 'df3':     name         color    type
     0  Chocolate    Brown    Sweet}
    In [234]:
    
    pd.concat(d.values(), ignore_index=True)
    Out[234]:
        name         color    type
    0  Banana       Red      Fruit
    1  Apple        Yellow   Fruit
    2  Chocolate    Brown    Sweet
    

    这假设您只是想连接所有 dfs,如果您要合并,那么您需要解释合并标准是什么

    【讨论】:

      猜你喜欢
      • 2020-12-23
      • 2021-12-28
      • 2021-08-03
      • 2021-12-03
      • 2022-01-15
      • 2021-02-10
      • 1970-01-01
      • 2016-03-08
      • 2018-05-13
      相关资源
      最近更新 更多