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 repeat each combination of rows in Dataframe ranging 1 to n?

Have got a dataframe df like below:

Store   Aisle   Table
11      59      2
11      61      3

Need to expand each combination of row 3 times generating new column ‘bit’ with range value as below:

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

Have tried the below code but didn’t worked out.

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(range(3))]

Help me out! Thanks in Advance.

>Solution :

You should provide a number, not a range to repeat. Also, you need a bit of processing:

(df.loc[df.index.repeat(3)]
   .assign(Bit=lambda d: d.groupby(level=0).cumcount().add(1))
   .reset_index(drop=True)
)

output:

   Store  Aisle  Table  Bit
0     11     59      2    1
1     11     59      2    2
2     11     59      2    3
3     11     61      3    1
4     11     61      3    2
5     11     61      3    3

Alternatively, using MultiIndex.from_product:

idx = pd.MultiIndex.from_product([df.index, range(1,3+1)], names=(None, 'Bit'))
(df.reindex(idx.get_level_values(0))
   .assign(Bit=idx.get_level_values(1))
)
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