gpt4 book ai didi

python - 如何根据 Pandas 另一列中的条件生成具有值的新列

转载 作者:行者123 更新时间:2023-11-28 20:12:31 24 4
gpt4 key购买 nike

我有一个如下所示的数据框,我需要生成一个名为“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对于测试成员,不匹配的值为 NaNs:

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

关于python - 如何根据 Pandas 另一列中的条件生成具有值的新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57955934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com