pandas 合并字典中的数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30233982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:20:47  来源:igfitidea点击:

Merge dataframes in a dictionary

pythonpandas

提问by qts

Say I have an dictionary of dataframes:

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

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

And I want to merge them all into one like this:

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

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

I can do it manually as follows:

我可以按如下方式手动完成:

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

But is there a way to automatically zip through the dictionary and merge? Any help is appreciated.

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

回答by EdChum

You can just pass the dict direct and access the valuesattribute to concat:

您可以直接传递 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

This assumes that you are just looking to concatenate all the dfs, if you are going to merge then you need to explain what the merge criteria is

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