本文介绍了如何根据 pandas 另一列中的条件生成具有值的新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数据框,我需要生成一个新列 Comment,对于指定的值,它应该显示 Fail

I have a dataframe as below, I need to generate a new column called "Comment" and for the values specified it should say "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


推荐答案

使用,不匹配的值是 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 ,并且空值使用:

If need assign Fail and empty values use 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

这篇关于如何根据 pandas 另一列中的条件生成具有值的新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 10:52