Search code examples
pythonpandasduplicatesrows

Python Pandas Duplicate all rows


I would like to duplicate all rows in my dataframe, so that the duplicate of each row is right below the original row. And then I want to add a new column with numpy.where function which would allow me to have different conditions for the original and duplicate rows. So that:

Name,Gender,Age
John,M,21
Mary,F,18
Peter,M,20

becomes:

Name,Gender,Age,Rename
John,M,21,Jo
John,M,21,hn
Mary,F,18,Ma
Mary,F,18,ry
Peter,F,20,Pe
Peter,F,20,er

I hope the example is clear. What is the best way to do this? (I am quite new to Python, so apologies if it's trivial)


Solution

  • ALternative:

    df = df.assign(Rename=list(
        zip(df.Name.str[:2], df.Name.str[-2:]))).explode('Rename')