我想仅在字段2和字段3不匹配时保存行。例如,在id“AAA”中,
id field2 field3
AAA SRE SRE
AAA FSD FRE
AAA TUE TUE
ABA SDE SDE
AAA FRT QRE
AAA HRE HRE
ABA EEE EEE
ABA URE FRE
如何使用if语句
保存到输出文件file = "/output.csv"
df.to_csv(file, sep="%", index=False)
答案 0 :(得分:4)
您可以这样做:
In [121]: df[df['field2']!=df['field3']]
Out[121]:
id field2 field3
1 AAA FSD FRE
4 AAA FRT QRE
7 ABA URE FRE
In [122]: df[df['field2']!=df['field3']].to_csv(file, sep="%", index=False)
In [123]: df = df[df['field2']==df['field3']]
In [124]: df
Out[124]:
id field2 field3
0 AAA SRE SRE
2 AAA TUE TUE
3 ABA SDE SDE
5 AAA HRE HRE
6 ABA EEE EEE