我有一个如下所示的数据框,我需要生成一个名为“ Comment”的新列,对于指定的值,它应该显示为“ Fail”
输入:
Tel MC WT
AAA Rubber 9999
BBB Tree 0
CCC Rub 12
AAA Other 20
BBB Same 999
DDD Other-Same 70
尝试过的代码:
df.loc[(df[WT] == 0 | df[WT] == 999 | df[WT] == 9999 | df[WT] == 99999),'Comment'] = 'Fail'
错误:
AttributeError: 'str' object has no attribute 'loc'
预期产量:
Tel MC WT Comment
AAA Rubber 9999 Fail
BBB Tree 0 Fail
CCC Rub 12
AAA Other 20
BBB Same 999 Fail
DDD Other-Same 70
使用Series.isin
测试会员,非匹配值NaN
S:
df.loc[df['WT'].isin([0, 999,9999,99999]),'Comment'] = 'Fail'
print (df)
Tel MC WT Comment
0 AAA Rubber 9999 Fail
1 BBB Tree 0 Fail
2 CCC Rub 12 NaN
3 AAA Other 20 NaN
4 BBB Same 999 Fail
5 DDD Other-Same 70 NaN
如果需要赋值Fail
和空值,请使用numpy.where
:
df['Comment'] = np.where(df['WT'].isin([0, 999,9999,99999]), 'Fail', '')
print (df)
Tel MC WT Comment
0 AAA Rubber 9999 Fail
1 BBB Tree 0 Fail
2 CCC Rub 12
3 AAA Other 20
4 BBB Same 999 Fail
5 DDD Other-Same 70
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句