2024-07-05 11:52:44 发布
网友
有许多类似的问题,但没有一个具体的。
我有一个数据帧列表,需要使用唯一的列(date)将它们合并在一起。字段名不同,所以concat不可用。
(date)
我可以手动使用df[0].merge(df[1],on='Date').merge(df[3],on='Date)等逐个合并每个df,但问题是列表中的数据帧数因用户输入而异。
df[0].merge(df[1],on='Date').merge(df[3],on='Date)
有没有什么方法可以一次合并列表中的所有数据帧?或者是一些循环中的?
我正在使用Python2.7。
您可以使用reduce函数,其中dfList是您的数据帧列表:
reduce
dfList
import pandas as pd 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
您可以使用
reduce
函数,其中dfList
是您的数据帧列表:作为演示:
相关问题 更多 >
编程相关推荐