【问题标题】:Filtering column value based on unique value, but not repeated for different value of the same column on the same unique value根据唯一值过滤列值,但对于同一唯一值的同一列的不同值不重复
【发布时间】:2021-01-22 22:54:46
【问题描述】:

寻找过滤具有inactive 状态的唯一值的方法,但在相同的唯一值下不重复为active 状态。

df:

Unique_value    Status
1               Active        <- Has both active and inactive, must be inactive only
1               Active        <- Has both active and inactive, must be inactive only
1               Inactive      <- Has both active and inactive, must be inactive only
1               Inactive      <- Has both active and inactive, must be inactive only
2               Inactive      <- Has inactive only
2               Inactive      <- Has inactive only
2               Inactive      <- Has inactive only
3               Inactive      <- Has inactive only (cancelled okay to be filtered out)
3               Cancelled     <- Has inactive only (cancelled okay to be filtered out)
3               Inactive      <- Has inactive only (cancelled okay to be filtered out)

期望的输出:

Unique_value    status
2               Inactive
3               Inactive

到目前为止我尝试过的,但我认为这是不正确的。

p = ['Inactive', 'Active']
df.groupby('Unique_value')['Status'].apply(lambda x: (x =='Inactive') != set(p))

【问题讨论】:

    标签: python-3.x pandas dataframe lambda apply


    【解决方案1】:

    首先检查每个组中的值any是Active还是Inactive。然后去掉两个条件都为真的组:

    m1 = df["Status"].eq("Active").groupby(df["Unique_value"]).transform("any")
    m2 = df["Status"].eq("Inactive").groupby(df["Unique_value"]).transform("any")
    df[~(m1 & m2)].groupby("Unique_value", as_index=False).first()
    
    
       Unique_value    Status
    0             2  Inactive
    1             3  Inactive
    

    【讨论】:

      【解决方案2】:

      我们试试

      g=df[df.groupby('Unique_value')['Status'].transform(lambda x: ~(x.eq('Active').any()))]
      
      g[g['Status'].eq('Inactive')].drop_duplicates()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-14
        • 2017-06-17
        • 2014-05-10
        相关资源
        最近更新 更多