Python中用于从一组交易中删除没有购买特定品牌/物品的用户的函数。

huangapple go评论61阅读模式
英文:

Function in python to remove users who haven't purchased a specific brand/item from a pool of transactions

问题

我试图根据购买特定品牌的情况对客户进行分段,一个分段是从未购买Volvic的用户,另一个是购买了Volvic水的用户,数据集包含了12个月的记录,按日期和交易级别(项目详情)记录。

基于上述每个段的标准,我需要检查在任何用户的trxn_ID中是否已购买Volvic,如果这个条件为真,则必须将用户从列表中移除,对于另一个分段则相反。

结果应该类似于以下内容:

从未购买Volvic:

User_ID
4567890

曾购买Volvic

User_ID
1234567
6543210

感谢任何帮助!

英文:

I'm trying to segment customers based on purchases for specific brands, one segment is for users who never bought Volvic and the other is users who have bought Volvic water, the dataset contains records of 12 months by date and transaction level (items details)

Date User_ID Trxn_ID Brand Item_description Price
1/1/23 1234567 100001 AQUA AQUA WATER 10x400ML 14
1/1/23 1234567 100001 VOLVIC VOLVIC WATER 330ML 1.7
1/1/23 1234567 100001 OSKA OSKA WATER 330 ML 0.5
1/19/23 1234567 100002 AQUA AQUA WATER 24x330ML 15
1/19/23 1234567 100002 OSKA OSKA WATER 10x330ML 5
1/19/23 6543210 100003 VOLVIC VOLVIC WATER 24x330ML 30
1/19/23 6543210 100003 AQUA AQUA WATER 24x330ML 15
1/1/23 4567890 100004 AQUA AQUA WATER 24x330ML 15
1/1/23 4567890 100004 OSKA OSKA WATER 10x330 ML 5

Based on the segments' criteria mentioned above for each, I need to check if Volvic has been purchased in any of the User's trxn_ID and if this condition is true then user has to be removed from the list, and vice versa for the other one.

The result should be something like below:

Never bought Volvic:

User_ID
4567890

Ever bought Volvic

| User_ID |
|---------|
| 1234567 |
| 6543210 |

Appreciate any help here!

答案1

得分: 0

df['check'] = df['Item_description'].str.contains('Volvic')
new_df = df[['User_ID', 'check']].groupby('User_ID').any()

英文:
df['check'] = df['Item_description'].str.contains('Volvic')
new_df = df[['User_ID', 'check']].groupby('User_ID').any()

This should do it.

  1. step 1 creates a boolean column which is True whenever a user bought Vovic
  2. step 2 groups by the user and return True or False if that user did or didn't buy Vovic

huangapple
  • 本文由 发表于 2023年2月8日 17:07:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定