Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading