Home > OS >  Python: How to replicate rows in Dataframe with column value but changing the column value to its ra
Python: How to replicate rows in Dataframe with column value but changing the column value to its ra

Time:12-08

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.

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

Thanks!

CodePudding user response:

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

CodePudding user response:

We can try explode

out = df.assign(Table=df['Table'].map(range)).explode('Table')
Out[160]: 
   Store  Aisle Table
0     11     59     0
0     11     59     1
1     11     61     0
1     11     61     1
1     11     61     2
  • Related