How to merge a single column of a list of dataframes with the same colum names into a new dataframe?

Question:

So I have a list of 10 dataframes:

dfs = [df1, df2, df3, df4, df5, df6, df7, df8, df9, df10]

All those dataframes follow the same format with the same column names:

Date, Price, High, Low

I’d like to create a new dataframe using Date and Price from every single one of those dataframes and change those column names to Price1, Price2, Price3, ... based on the dataframe it’s being pulled from. The result would look like this: Date, Price1, Price2, Price3, ... ,Price10 as columns. Is there a fancy way of doing this?

Asked By: student

||

Answers:

Here’s one way to do it. The frames are aligned on the Date column.

result = pd.concat(
    [df.set_index("Date")["Price"].rename(f"Price{i+1}") for i, df in enumerate(dfs)],
    axis=1,
)

You can then reset or keep Date on the index.

Answered By: Code Different
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.