首页 > 解决方案 > 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 函数,我从来没有做过这样的事情,以前有条件检查

标签: pythonpandaspandas-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

推荐阅读