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

Repeating each item a different number of times

I have a dataframe with a column with item names and a column with a number. I would like to create a list with the item names repeated the number of times in the column.

item number
cat 2
dog 3
parrot 4

My desired output is

item
cat
cat
dog
dog
dog
parrot
parrot
parrot
parrot

I feel like I’m quite close with this code:

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

for index in df.iterrows():
    for x in range(2):
        print(df.item)

However, I can’t find a way to replace 2 in range with the number out of the dataframe. df.numbers doesn’t seem to work.

>Solution :

As you said, your desired output is a list, using @Michael’s comment, you can do this:

list(df.item.repeat(df.number))

The output would be:

['cat', 'cat', 'dog', 'dog', 'dog', 'parrot', 'parrot', 'parrot', 'parrot']
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