pandas 合并数据框列表以创建一个数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38978214/
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-14 01:49:50  来源:igfitidea点击:

Merge a list of dataframes to create one dataframe

pythonpython-3.xpandas

提问by Josh

I have a list of 18 data frames:

我有一个包含 18 个数据框的列表:

dfList = [df1, df2, df3, df4, df5, df6.....df18]

All of the data frames have a common id column so it's easy to join them each together with pd.merge 2 at a time. Is there a way to join them all at once so that dfList comes back as a single dataframe?

所有的数据框都有一个共同的 id 列,因此很容易一次将它们与 pd.merge 2 连接在一起。有没有办法一次将它们全部加入,以便 dfList 作为单个数据帧返回?

回答by jezrael

I think you need concat, but first set index of each DataFrameby common column:

我认为您需要concat,但首先DataFrame按公共列设置每个索引:

dfs = [df.set_index('id') for df in dfList]
print pd.concat(dfs, axis=1)

If need join by merge:

如果需要加入merge

df = reduce(lambda df1,df2: pd.merge(df1,df2,on='id'), dfList)