我有一个看起来像这样的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()
但它仅提供汇总计数,而不提供用户计数。如何获得用户的垃圾箱计数?
总计计数(使用我的真实数据)如下所示:
impressions (2500, 5000] 2332 (5000, 10000] 1118 (10000, 50000] 570 (50000, 10000000] 14 Name: username, dtype: int64
您可以按垃圾箱 和 用户名分组,计算分组大小,然后使用unstack():
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