如何解决如何使用for循环和if语句将行追加到pandas数据框
如果每行都符合条件,我将尝试将这些行复制并追加到数据帧中,如'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
现在,我还不太清楚这段代码的错误,而且我不确定如何解决错误。
解决方法
这里不需要循环,只需使用qty1
字段中传递的Index.repeat
作为重复即可。然后使用loc
返回行。
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。