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 can I duplicate the first row of a dataframe to the length of the dataframe using Pandas

I would like duplicate the first row of this dataframe but keep the index and the first column the same. I cant find a way of leaving the first column the same.

This is just a minimized example I have 1000 rows that I am working with.

This is what is tried:

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

import numpy as np
import pandas as pd
df = pd.DataFrame({'X':[1,2,3,4,5], 'Y':[84,94,89,83,86],'Z':[86,97,96,72,83]});

df.iloc[np.arange(1).repeat(len(df))].reset_index(drop=True)

This is what I am looking for

({'X':[1,2,3,4,5], 'Y':[84,84,84,84,84],'Z':[86,86,86,86,86]});

>Solution :

Just specify the columns you want, and use .loc:

cols = ['Y', 'Z']
df.loc[:, cols] = df.loc[0, cols].to_numpy()

Output:

>>> df
   X   Y   Z
0  1  84  86
1  2  84  86
2  3  84  86
3  4  84  86
4  5  84  86

Or, if you would rather specify the columns you don’t want, use df.columns.difference:

cols = df.columns.difference(['X'])
df.loc[:, cols] = df.loc[0, cols].to_numpy()
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