mercredi 12 août 2020

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.

Aucun commentaire:

Enregistrer un commentaire