有许多类似的问题,但没有一个专门针对此问题。
我有一个数据帧列表,我需要使用唯一列将它们合并在一起(date)
。字段名称不同,因此concat退出了。
我可以手动使用df[0].merge(df[1],on='Date').merge(df[3],on='Date)
等将每个df逐一合并,但是问题是列表中数据帧的数量随用户输入而不同。
有什么合并方法可以一次将所有数据帧合并到一个列表中?还是有一些for in loop这样做的?
我正在使用Python 2.7。
您可以使用reduce
函数wheredfList
是数据帧列表:
import pandas as pd
from functools import reduce
reduce(lambda x, y: pd.merge(x, y, on = 'Date'), dfList)
作为演示:
df = pd.DataFrame({'Date': [1,2,3,4], 'Value': [2,3,3,4]})
dfList = [df, df, df]
dfList
# [ Date Value
# 0 1 2
# 1 2 3
# 2 3 3
# 3 4 4, Date Value
# 0 1 2
# 1 2 3
# 2 3 3
# 3 4 4, Date Value
# 0 1 2
# 1 2 3
# 2 3 3
# 3 4 4]
reduce(lambda x, y: pd.merge(x, y, on = 'Date'), dfList)
# Date Value_x Value_y Value
# 0 1 2 2 2
# 1 2 3 3 3
# 2 3 3 3 3
# 3 4 4 4 4
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句