Python 如何使用for循环和if语句将行附加到数据帧

Python 如何使用for循环和if语句将行附加到数据帧,python,pandas,dataframe,for-loop,if-statement,Python,Pandas,Dataframe,For Loop,If Statement,如果每一行都符合条件,我会尝试将这些行复制并附加到数据帧中,次数如“qty1”中所示 以下是我迄今为止尝试的代码: 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():

如果每一行都符合条件,我会尝试将这些行复制并附加到数据帧中,次数如“qty1”中所示

以下是我迄今为止尝试的代码:

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
我得到以下结果(但什么也没发生):

而我要找的是:

    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

现在,我不太清楚这段代码的错误,我只是不知道如何修复bug。

这里不需要循环,只需使用传递
qty1
字段作为重复。然后使用返回行

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

df.loc[df.index.repeat(df['qty1'])].reset_index(drop=True)
  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