How to append rows to pandas dataframe with for loop and if statements

I am trying to copy and append the lines to the dataframe, if each line meets the condition, as many times as indicated in 'qty1'.

Here are the codes I have attempted thus far:

import pandas as pd
row_list = [['a', 1, 4], ['b', 2, 5], ['c', 3, 6]]
columns = ['item', 'qty1', 'qty2']

df = pd.DataFrame(row_list, columns = columns)

for index, row in df.iterrows():
    if df.loc[index, 'qty1'] != 1: # apply only on lines where 'qty1' is different from 1
        df.append([row]*df.loc[index,'qty1']) # multiply and append the rows as many times as the column 'qty1' indicates
    else:
        pass

df

I get the following result (but nothing happens):

    item qty1 qty2
0      a    1    4
1      b    2    5
2      c    3    6

While what I am looking for is this:

    item    qty1    qty2
0      a       1       4
1      b       2       5
2      b       2       5
3      c       3       6
4      c       3       6
5      c       3       6

Now, I am not well aware of the faults of this code and I am just not sure how to bug fix.

Upvotes: 0

Views: 1137

Answers (1)

Chris Adams
Chris Adams

Reputation: 18647

You don't need a loop here, just use Index.repeat passing in the qty1 field as the repetitions. Then use loc to return the rows.

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

[out]

  item  qty1  qty2
0    a     1     4
1    b     2     5
2    b     2     5
3    c     3     6
4    c     3     6
5    c     3     6

Upvotes: 2

Related Questions