python - Pandas - groupby ID 输入一个后选择购买的物品
问题描述
我有一个像这样的数据框:
df = pd.DataFrame({"ID": [123214, 123214, 321455, 321455, 234325, 234325, 234325, 234325, 132134, 132134, 132134],
"DATETIME": ["2020-05-28", "2020-06-12", "2020-01-06", "2020-01-10", "2020-01-11", "2020-02-06", "2020-07-24", "2020-10-14", "2020-03-04", "2020-09-11", "2020-10-17"],
"CATEGORY": ["computer technology", "early childhood", "early childhood", "shoes and bags", "early childhood", "garden and gardening", "musical instruments", "handmade products", "musical instruments", "early childhood", "beauty"]})
我想:
- 按 ID 分组
- where CATEGORY == “early children”(输入),选择下一个购买的物品(下一行)
结果应该是:
321455 "2020-01-10" "shoes and bags"
234325 "2020-02-06" "garden and gardening"
132134 "2020-10-17" "beauty"
Pandas 的 shift 功能是我所需要的,但我无法在分组时使其工作。谢谢!
解决方案
CATEGORY
您可以通过Series.eq
with创建带有 test 的掩码DataFrameGroupBy.shift
,将第一个缺失值替换为False
并传递给boolean indexing
:
#if necessary convert to datetimes and sorting
#df['DATETIME'] = pd.to_datetime(df['DATETIME'])
#df = df.sort_values(['ID','DATETIME'])
mask = df['CATEGORY'].eq('early childhood').groupby(df['ID']).shift(fill_value=False)
df = df[mask]
print (df)
ID DATETIME CATEGORY
3 321455 2020-01-10 shoes and bags
5 234325 2020-02-06 garden and gardening
10 132134 2020-10-17 beauty
推荐阅读
- azure - Powershell 中的 Azure 新 VM -AvailabitySetname
- c - 将指针写入 GPIO 输出引脚的地址
- c - 如何使用 pthread 实现单写入器、多读取器队列?
- angular - 尝试到达 Angular Universal (SSR) 路线给出 404(无法获取)
- c# - 在 Linq 中想要这个 Sql 查询
- php - 无法使用 PHP 删除数据库中的行
- python - 从 TBODY 中提取 TD
- c# - 哪个更适合编译和执行禅?if(a == null) 或 a?
- ios - Xcode 11 GM 中缺少 iOS 12.4
- python - __defaults__ 显式默认以克服可变问题