在熊猫中过滤、分组和计数?

Ahm*_*mal 2 python dataset python-3.x pandas

TSV 文件包含一些用户事件数据:

user_uid category event_type
"11"      "like"   "post"
"33"      "share"  "status"
"11"      "like"   "post"
"42"      "share"  "post"
Run Code Online (Sandbox Code Playgroud)

获取post每个类别和每个 user_id的事件数量的最佳方法是什么?

我们应该显示以下输出:

user_uid category count
"11"     "like"    2
"42"     "share"   1
Run Code Online (Sandbox Code Playgroud)

ALo*_*llz 5

清理任何尾随空格,以便正确分组。过滤您的DataFrame,然后应用groupby+size

df['category'] = df.category.str.strip()
df['user_uid'] = df.user_uid.str.strip()
df[df.event_type == 'post'].groupby(['user_uid', 'category']).size()
Run Code Online (Sandbox Code Playgroud)

输出:

user_uid  category
11        like        2
42        share       1
dtype: int64
Run Code Online (Sandbox Code Playgroud)