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

Duplicate rows in pandas on condition

I have this pandas dataframe:

    Column1   Column2    Column3
1     A                     C
2     A         D   
3     B

If the is a "D" in my column2 i want to duplicate the row with is values and reset the index like this :

    Column1  Column2    Column3
1     A                    C
2     A         D   
3     A         D   
4     B

How do I do this in pandas?

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

>Solution :

First test if duplicated columns names, if necessary deduplicate them:

print (df.columns[df.columns.duplicated(keep=False)])

Then join filtered rows with concat and sort indices:

df = df.reset_index(drop=True)

df = (pd.concat([df, df[df['Column2'].eq('D')]])
        .sort_index(kind='stable', ignore_index=True)
        .rename(lambda x: x+1))
print (df)
  Column1 Column2 Column3
1       A     NaN       C
2       A       D     NaN
3       A       D     NaN
4       B     NaN     NaN
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