Home > Enterprise >  Merging multiple dataframes that all have a indexed ['Date'}
Merging multiple dataframes that all have a indexed ['Date'}

Time:10-24

I have a list of dataframes all have a ['Date'] column set as the index

data_frames = [df1, df2, df3, df4, df5]

I would like to merge them all on the index I found the below code but it obviously wont work in my case because it only merges 2 dataframes. Is there anyways to do it with a list in one step?

final_df = reduce(lambda left,right: pd.merge(left_index=True, right_index=True, how='inner'), data_frames)

CodePudding user response:

import pandas as pd

df1 = pd.DataFrame({"Date":[1,2]})
df2 = pd.DataFrame({"Date":[1,2,3]})
df3 = pd.DataFrame({"Date":[3]})
df4 = pd.DataFrame({"Date":[1,2,3,4]})
df5 = pd.DataFrame({"Date":[4]})
data_frames = pd.concat([df1, df2, df3, df4, df5])
print(data_frames)

CodePudding user response:

import pandas as pd
from functools import reduce


df_final = reduce(lambda left, right: pd.merge(left, right, on="Date", how="inner"), [x.reset_index() for x in dataframes]).set_index("Date")
  • Related