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

Time:01-22

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?

CodePudding user response:

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 Data on the index.

  • Related