具有箱计数的Pandas分组

gk7wooem  于 2023-03-21  发布在  其他
关注(0)|答案(2)|浏览(157)

我有一个DataFrame,看起来像这样:

+----------+---------+-------+
| username | post_id | views |
+----------+---------+-------+
| john     |       1 |     3 |
| john     |       2 |    23 |
| john     |       3 |    44 |
| john     |       4 |    82 |
| jane     |       7 |     5 |
| jane     |       8 |    25 |
| jane     |       9 |    46 |
| jane     |      10 |    56 |
+----------+---------+-------+

我想把它转换成计数属于某些bin的视图,如下所示:

+------+------+-------+-------+--------+
|      | 1-10 | 11-25 | 25-50 | 51-100 |
+------+------+-------+-------+--------+
| john |    1 |     1 |     1 |      1 |
| jane |    1 |     1 |     1 |      1 |
+------+------+-------+-------+--------+

我试过:

bins = [1, 10, 25, 50, 100]
groups = df.groupby(pd.cut(df.views, bins))
groups.username.count()

但它只给出了聚合计数,而不是按用户计数。我如何才能按用户获得bin计数?
聚合计数(使用我的真实的数据)如下所示:

impressions
(2500, 5000]         2332
(5000, 10000]        1118
(10000, 50000]        570
(50000, 10000000]      14
Name: username, dtype: int64
vyswwuz2

vyswwuz21#

你可以用bin * 和 * username进行分组,计算组的大小,然后使用unstack()

>>> groups = df.groupby(['username', pd.cut(df.views, bins)])
>>> groups.size().unstack()
views     (1, 10]  (10, 25]  (25, 50]  (50, 100]
username
jane            1         1         1          1
john            1         1         1          1
e1xvtsh3

e1xvtsh32#

跨组计数是pd.crosstab的一项工作:

bins = [1, 10, 25, 50, 100]
pd.crosstab(df['username'], pd.cut(df['views'], bins))

等效的pivot_table也可以工作:

df.pivot_table(index='username', columns=pd.cut(df['views'], bins), aggfunc='size')

使用rename_axis()删除索引名称:

pd.crosstab(df['username'], pd.cut(df['views'], bins)).rename_axis(columns=None, index=None)

          (1, 10]  (10, 25]  (25, 50]  (50, 100]
 jane           1         1         1          1
 john           1         1         1          1

相关问题