python pandas标志是否每个列中的每个值都有一个以上的唯一行 [英] python pandas flag if more than one unique row per value in column

查看:347
本文介绍了python pandas标志是否每个列中的每个值都有一个以上的唯一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的DataFrame中,我有三列:

In the following DataFrame, I have three columns:

   Code      |   Category  |    Count
     X               A          89734
     X               A          239487
     Y               B          298787
     Z               B          87980
     W               C          098454

我需要添加一列,如果一个类别具有多个唯一代码(如上面的示例中的B),它将得到一个标志,表示它是一个测试.

I need to add a column, that if a category has more than one unique code (like B in the example above), it gets a flag denoting it as a test.

所以我正在寻找的输出是这样:

So the output I am looking for is this:

   Code      |   Category  |    Count    | Test_Flag
     X               A          89734       
     X               A          239487
     Y               B          298787         T
     Z               B          87980          T
     W               C          098454

推荐答案

您还可以选择

You could also opt for transform with numpy.where for filling the values.

df['Test_flag'] = np.where(df.groupby('Category').Code.transform('nunique') > 1, 'T', '')


>>> df
  Category Code   Count Test_flag
0        A    X   89734          
1        A    X  239487          
2        B    Y  298787         T
3        B    Z   87980         T
4        C    W   98454          

这篇关于python pandas标志是否每个列中的每个值都有一个以上的唯一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆