【问题标题】:Get all customers who have multiple specific values in a column获取列中具有多个特定值的所有客户
【发布时间】:2020-06-09 10:22:15
【问题描述】:

我该怎么做?:

获取同时给出名字 (name_fist) 和生日的所有客户。

df = pd.DataFrame({
     'customer_ID': ['a','a', 'a', 'b', 'c', 'c', 'c', 'd', 'd'],
     'parameter': ['name_fist', 'name_last', 'birthday', 'name_fist', 
                   'name_fist', 'name_last', 'birthday', 'name_fist', 'name_last']})

customer_ID   parameter
0   a    name_fist
1   a    name_last
2   a    birthday
3   b    name_fist
4   c    name_fist
5   c    name_last
6   c    birthday
7   d    name_fist
8   d    name_last

答案应该是“2”。

理想情况下,我会得到所有满足此条件的人的客户 ID:a 和 c

【问题讨论】:

    标签: pandas filter


    【解决方案1】:

    你可以试试这样的:

    (df.query('parameter in ["name_fist", "birthday"]')\
       .groupby('customer_ID')['parameter'].nunique() == 2)
    

    输出:

    customer_ID
    a     True
    b    False
    c     True
    d    False
    Name: parameter, dtype: bool
    

    详情:

    首先使用query 过滤数据框以获取感兴趣的参数,然后使用groupby 并使用nunique 来计算参数。

    【讨论】:

      【解决方案2】:

      一种方法是groupbycustomer_ID 然后通过set.issuperset 进行检查(请注意,您的拼写错误是“name_fist”而不是“first”:

      print (df.groupby("customer_ID")["parameter"]
             .apply(lambda d: set(d).issuperset({"name_fist","birthday"})))
      
      #
      customer_ID
      a     True
      b    False
      c     True
      d    False
      Name: parameter, dtype: bool
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-14
        • 2016-03-04
        • 1970-01-01
        • 2014-01-30
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多