筛选,分组并统计熊猫?

时间:2018-08-06 15:43:40

标签: python python-3.x pandas dataset

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

user_uid category event_type
"11"      "like"   "post"
"33"      "share"  "status"
"11"      "like"   "post"
"42"      "share"  "post"

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

我们应该显示以下输出:

user_uid category count
"11"     "like"    2
"42"     "share"   1

1 个答案:

答案 0 :(得分:3)

清理所有结尾的空格,以便正确分组。过滤您的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()

输出:

user_uid  category
11        like        2
42        share       1
dtype: int64