![](/img/trans.png)
[英]Counting unique values in a subset of grouped rows in a Pandas dataframe. (I did my best with the title)
[英]Counting unique values in a pandas grouped object
我在pandas / python中有一張表,並且正在執行以下操作:
grouped_data = df_comments_cols ['article_id']。groupby(df_comments_cols ['user_id'])
現在,要計算每個用戶的文章數,請執行以下操作:
ct_grouped_data = grouped_data.count()
以上計算了每個用戶的文章ID數。 但是,有時每個用戶有多個相同的商品ID(從某種意義上說,一個用戶與該商品進行了多次交互),而我只希望為每個用戶計算唯一的商品ID-有一種快速的方法嗎?
提前致謝。
我認為您可能正在尋找的是nunique
,您可以像這樣調用GroupBy
對象:
In [63]: df = DataFrame({'a': randn(1000, 1)})
In [64]: df['user_id'] = randint(100, 1000, size=len(df))
In [65]: df['article_id'] = randint(100, size=len(df))
In [66]: gb = df.article_id.groupby(df.user_id)
In [67]: gb.nunique()
Out[67]:
user_id
100 2
101 1
102 1
104 2
105 1
106 2
107 1
110 1
111 4
112 2
113 1
114 2
115 1
116 1
118 1
...
976 3
980 1
982 1
983 1
986 1
987 1
988 1
989 2
990 1
993 1
994 2
996 1
997 1
998 1
999 1
Length: 617, dtype: int64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.