Python List Duplication

Viewed 42

I'm fairly new to Python and StackOverflow, so forgive me for my terrible formatting. I had a question about duplicating rows in a DataFrame. I have a data set that looks like this.

WEIGHT AGE DEBT ASSETS
2 34 4000 10000
3 42 3000 4000

I would like to duplicates the rows by the WEIGHT, so I will end up with the following:

WEIGHT AGE DEBT ASSETS
2 34 4000 10000
2 34 4000 10000
3 42 3000 4000
3 42 3000 4000
3 42 3000 4000

I don't have a clue where to start and would appreciate any help!

1 Answers

You can use Index.repeat and then reindex the dataframe:

print(df.reindex(df.index.repeat(df["WEIGHT"])))

Prints:

   WEIGHT  AGE  DEBT  ASSETS
0       2   34  4000   10000
0       2   34  4000   10000
1       3   42  3000    4000
1       3   42  3000    4000
1       3   42  3000    4000
Related