Search code examples
pythondataframedivision

Divide quantities in order to get one quantity per row - python


I have a dataframe with quantities and prices. I would like to get an dataframe with same prices vs quantity but only one quantity per line.

Dataframe:

Name | qty | Price
Apple | 3 | 3.50
Avocado | 2 | 1.50

Expected Output:

Name | qty| Price
Apple | 1 | 3.50
Apple | 1 | 3.50
Apple | 1 | 3.50
Avocado | 1 | 1.50
Avocado | 1 | 1.50

honestly don't know how to code this in a pythonic way.


Solution

  • We can use df.index.repeat, then set the qty to 1 for all rows.

    df = df.loc[df.index.repeat(df['qty'])].reset_index(drop=True)
    df['qty'] = 1
    

    Output:

          Name  qty  Price
    0    Apple    1    3.5
    1    Apple    1    3.5
    2    Apple    1    3.5
    3  Avocado    1    1.5
    4  Avocado    1    1.5