Pandas 带 bin 计数的 groupby
Pandas groupby with bin counts
我有一个如下所示的 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 |
+----------+---------+-------+
我想将其转换为计算属于某些垃圾箱的视图,如下所示:
+------+------+-------+-------+--------+
| | 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
您可以按 bins 和 用户名分组,计算组大小,然后使用 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
我有一个如下所示的 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 |
+----------+---------+-------+
我想将其转换为计算属于某些垃圾箱的视图,如下所示:
+------+------+-------+-------+--------+
| | 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
您可以按 bins 和 用户名分组,计算组大小,然后使用 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