python pandas 仅对一个类别应用 if 语句和 groupby

标签 python pandas if-statement group-by

这个问题的小 pig 支持python pandas flag if more than one unique row per value in column

我只想将以下规则仅应用于类型为 X 的行。

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

数据框 df:

    Code      |  Type  | Category  |    Count
    code1          Y        A          89734
    code1          Y        A          239487
    code2          Z        B          298787
    code3          Z        B          87980
    code4          Y        C          098454
    code5          X        D          298787
    code6          X        D          87980

预期结果:

    Code      |  Type  | Category  |    Count  | Test Flag
    code1          Y        A          89734
    code1          Y        A          239487
    code2          Z        B          298787
    code3          Z        B          87980
    code4          Y        C          098454
    code5          X        D          298787       T
    code6          X        D          87980        T

说明:

  1. 类别 A 具有相同的代码,但不是类型 X -> 因此没有标记 T
  2. B 类有不同的代码,但不是 X 类 -> 因此没有标记 T
  3. C 类只有一个代码,不是 X 类 -> 因此没有标志 T
  4. D 类有不同的代码,属于 X 型-> FLAG T

我试过了

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

我收到以下错误:

ValueError: operands could not be broadcast together with shapes (1,2199) (7620,)

最佳答案

逻辑与中缺少括号,这将导致条件中的运算顺序解析不正确。除此之外,你的逻辑看起来应该有效。

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

最小演示

>>> df 
  Category   Code  Count Type
0        A  code1      1    Y
1        A  code1      2    Y
2        B  code2      3    Z
3        B  code3      4    Z
4        C  code4      5    Y
5        D  code5      4    X
6        D  code6      2    X

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

>>> df
  Category   Code  Count Type Test_flag
0        A  code1      1    Y          
1        A  code1      2    Y          
2        B  code2      3    Z          
3        B  code3      4    Z          
4        C  code4      5    Y          
5        D  code5      4    X         T
6        D  code6      2    X         T

关于python pandas 仅对一个类别应用 if 语句和 groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42497017/

相关文章:

python - 将 Levenshtein 比率转换为 C++

python - 如何使用 Python 根据另一个 DataFrame 中的行选择 DataFrame 中的行

file - 批处理文件第三个 "If NOT"语句未到达

c# - 如何访问用户控件中的 i 语句

java - 将数据从 Java 传递到 Python

python - 由于垃圾收集错误,c python 扩展导致 python 脚本以段错误退出

python - 使用多个键之一过滤字典

python - 在 Pandas 中处理日期 - 删除日期时间中看不见的字符并转换为字符串

python - 如何替换最后 2 个字符(如果在 python 中可用)

javascript - 检查某个项目是否已在数组中的正确 jquery 语法是什么?这是一个简单的例子