python - Python Pandas 按类别标记分组
问题描述
我有一个像这样的数据框:
|transaction_id|category|
-------------------------
|1234 |Book |
|1234 |Car |
|1234 |TV |
|1235 |Car |
|1235 |TV |
|1236 |Car |
基本上,我想按 transaction_id 分组并创建一个列来标记 transaction_id 在类别列中是否有相应的电视,因此理想情况下,生成的数据框如下所示:
|transaction_id|HasTV?|
-----------------------
|1234 |Y |
|1235 |Y |
|1236 |N |
我正在使用熊猫,我知道如何使用 groupby 函数,我从来没有做过这样的事情,以前有条件检查
解决方案
一种选择是查看.unique()
类别,然后对结果系列进行操作:
In [28]: df.groupby("transaction_id")['category'].unique().apply(lambda x: 'TV' in x)
Out[28]:
transaction_id
1234.0 True
1235.0 True
1236.0 False
Name: category, dtype: bool
另一个可能更快但更模糊的版本是预先测试所需的类别,然后执行 groupby:
In [29]: (df['category'] == 'TV').groupby(df["transaction_id"]).max()
Out[29]:
transaction_id
1234.0 True
1235.0 True
1236.0 False
Name: category, dtype: bool
推荐阅读
- python - 用于更新 Conda-Forge 原料的持续集成
- xamarin.forms - Azure B2C Xamarin Forms,clientId 与 applicationId
- css - 在 GTK 中限制主题 CSS 的标签大小?
- android - AdMob RewardedAd 导致内存泄漏 (v19.7.0)
- network-drive - 尝试访问 Windows 10 桌面上已装载的 Azure 文件共享时,文件资源管理器挂起
- firebase - 如何在flutter应用程序中为firestore配置多个条件查询
- kubernetes - 如何获取 prometheus 中节点/pod 的 cpu 和内存使用情况?
- nginx - 在 AKS 中使用 NGINX 在 POD 中缺少 Dapr Side-Car
- jestjs - create-react-app 和 jest - 不能在模块外使用 import 语句
- mysql - 从 SQL 中收集最近 7 天的数据并按天分组