繁体   English   中英

过滤 dataframe 中至少有一行满足条件的所有行

[英]Filtering all rows in dataframe where at least one row meets a condition

我有一个 dataframe 有一个客户列表和他们购买的产品实例。 我正在尝试获得一个新的 dataframe,它排除了至少购买过一次特定产品的所有客户。 例如:

d = {'Customer': ['Cust 1', 'Cust 1', 'Cust 2', 'Cust 1', 'Cust 2', 'Cust 2', 'Cust 3', 'Cust 3'], 
     'Product': [1, 1, 2, 1, 1, 2, 2, 1], 
     'PO': ['P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8']}

df = pd.DataFrame(data=d)
df

Output

| |Customer |Product   |PO        |
| |:--------|:---------|:---------|
|0| Cust 1  |  1       |  P1      |
|1| Cust 1  |  1       |  P2      |
|2| Cust 2  |  2       |  P3      |
|3| Cust 1  |  1       |  P4      |
|4| Cust 2  |  1       |  P5      |
|5| Cust 2  |  2       |  P6      |
|6| Cust 3  |  2       |  P7      |
|7| Cust 3  |  1       |  P8      |

我希望能够过滤掉任何在任何阶段购买了产品 2 的客户,无论他们还购买了什么,例如:

| |Customer |Product   |PO        |
| |:--------|:---------|:---------|
|0| Cust 1  |  1       |  P1      |
|1| Cust 1  |  1       |  P2      |
|2| Cust 1  |  1       |  P4      |

有没有办法做到这一点? 任何帮助将不胜感激!

使用pandas.DataFrame.groupby.filter

new_df = df.groupby("Customer").filter(lambda x: 2 not in set(x["Product"]))
print(new_df)

Output:

  Customer  Product  PO
0   Cust 1        1  P1
1   Cust 1        1  P2
3   Cust 1        1  P4
k = df[df['PO']=='P2']['Customer']
df[df['Customer'].isin(k)]

期望的结果

    Customer    Product PO
0   Cust 1          1   P1
1   Cust 1          1   P2
3   Cust 1          1   P4
df[~df.Customer.isin(df[df.Product == 2]['Customer'])]

您可以通过以下几种方式做到这一点:

  1. groupbyfilterall一起使用:

df.groupby('Customer').filter(lambda x: (x['Product'].= 2).all())

  1. groupbytransformall与 boolean 索引一起使用:

df[df.groupby('Customer')['Product'].transform(lambda x: (x.= 2).all())]

Output:

  Customer  Product  PO
0   Cust 1        1  P1
1   Cust 1        1  P2
3   Cust 1        1  P4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM