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

Python: How to replicate rows in Dataframe with column value but changing the column value to its range

Have got a dataframe df

Store   Aisle   Table
11      59      2
11      61      3

Need to replicate these rows w.r.t. column ‘Table’ times on changing ‘Table’ column value as below:

Store   Aisle   Table
11      59      1
11      59      2
11      61      1
11      61      2
11      61      3

Tried below code, but this doesn’t change the value instead replicates the same row n times.

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

df.loc[df.index.repeat(df['Table'])]

Thanks!

>Solution :

You can do a groupby().cumcount() after that:

out = df.loc[df.index.repeat(df['Table'])]
out['Table'] = out.groupby(level=0).cumcount() + 1

Output:

   Store  Aisle  Table
0     11     59      1
0     11     59      2
1     11     61      1
1     11     61      2
1     11     61      3
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