【问题标题】:Merge a list of dataframes to create one dataframe [duplicate]合并数据框列表以创建一个数据框[重复]
【发布时间】:2016-12-23 00:34:59
【问题描述】:

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

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

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

【问题讨论】:

  • 能否详细说明循环选项?听起来像我要找的东西

标签: python python-3.x pandas


【解决方案1】:

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

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

如需加入merge:

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

【讨论】:

  • pd.concat(dfList, axis=1) 将它们全部组合在一起,但每个 df 都有自己的行(因此每个 id 都重复了 18 次)
  • 我试着写成变量:sdf = pd.concat(dfs, axis=1) 得到了TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame" 不明白。
猜你喜欢
  • 2022-01-15
  • 1970-01-01
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 2020-09-17
  • 2018-02-13
  • 2021-09-21
  • 2018-09-17
相关资源
最近更新 更多