【发布时间】:2020-08-12 11:29:22
【问题描述】:
如果每行符合条件,我正在尝试复制这些行并将其附加到数据框中,次数与“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 c 3 6
虽然我正在寻找的是:
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
现在,我不太清楚这段代码的错误,我只是不知道如何修复错误。
【问题讨论】:
标签: python pandas dataframe for-loop if-statement