簡體   English   中英

過濾,分組並計算熊貓?

[英]Filter , group by and count in pandas?

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

清理任何尾隨空格,以便正確分組。 過濾您的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM