Py学习  »  Python

python pandas使用类别标志分组

DBA108642 • 6 年前 • 1748 次点击  

我有一个这样的数据框:

|transaction_id|category|
-------------------------
|1234          |Book    |
|1234          |Car     |
|1234          |TV      |
|1235          |Car     |
|1235          |TV      |
|1236          |Car     |

基本上,我想按事务id分组,并创建一个列来标记事务id在category列中是否有相应的tv,因此理想情况下生成的数据帧如下所示:

|transaction_id|HasTV?|
-----------------------
|1234          |Y     |
|1235          |Y     |
|1236          |N     |

我用的是pandas,我知道如何使用groupby函数,我从来没有做过这样的事情,以前有条件检查

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/41175
文章 [ 1 ]  |  最新文章 6 年前
Randy
Reply   •   1 楼
Randy    6 年前

一种选择是看 .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