I need to add data from other dataframes to a dataframe, using the merge function, to ensure that it only takes those values whose indices have the same date. The statement that I show below returns the error mentioned in the Title.
df_total = pd.merge(cotiz_diaria, [df, df1, df2, df3, df4, df5, df6, df7, df8, df9, df10, df11, df12], left_index=True, right_index=True)
df_df_total
The error seems to indicate that it doesn't support df lists.
How else could I do this join, other than adding each dataframe one by one?
Indeed, your diagnosis is correct. What happens is that
merge()
it does not accept a list ofDataframe
at most two of these objects is allowed to be passed to it. But you can iterate over the list and do the process ofmerge
. For example:We have created a list
dfs
containing 3DataFrame
, now we can do themerge
:Detail:
With we
dfs = iter(dfs)
convert the list into aiterador
, this is because of the way we are going to process, as we need the first element on the one hand and then the rest, it is preferable to do it this way and avoid making copies of lists.With
df_final = next(dfs)
we initialize theDataFrame
end with the first object of the listThen we simply iterate over the next elements of the list and with it
df_final = df_final.merge(df_, left_index=True, right_index=True)
we do the onemerge
of each object.An identical result but with fewer lines of code is to use the function
reduce()