Pandas DataFrame如何分组数值列的垃圾箱,然后对其他二进制列进行计数

发布于 2025-01-20 13:32:06 字数 430 浏览 2 评论 0原文

我有一个数据框:

c1 c2  SED f
1  2   0.2 1
3  3   0.7 1
3  1   0.1 0
8  1   0.6 0
9  2   1   1
4  9   8.3 1

我想将 SED 分组到宽度为 0.5 的 bin 和 foreach bin,计算列 f 为 1 的行数及其行数0.

所以对于这个例子我会得到:

SED_bin   cou_0   cou_1     
  0-0.5     1       1
  0.5-1     1       2
  8-8.5     0       1 

最好的方法是什么? 请注意,这只是 SED 值的一个示例,可能还有更多低于或高于此范围的值,因此我需要通用的分箱。

I have a dataframe:

c1 c2  SED f
1  2   0.2 1
3  3   0.7 1
3  1   0.1 0
8  1   0.6 0
9  2   1   1
4  9   8.3 1

I want to group SED to bins of width 0.5 and foreach bin, count the number of rows the column f is 1 and the number of rows it is 0.

So for this example I will get:

SED_bin   cou_0   cou_1     
  0-0.5     1       1
  0.5-1     1       2
  8-8.5     0       1 

What is the best way to do it?
Please note this is just an example of SED values and there could be more below to above this range so I need the binning to be generic.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮华 2025-01-27 13:32:06

一个选项是使用剪切 + crosstab

out = (pd.crosstab(pd.cut(df['SED'], np.arange(int(df['SED'].min()), int(df['SED'].max())+1, 0.5)), df['f'])
       .add_prefix('count_').rename_axis(index='SED_bins').reset_index())

输出:

f    SED_bins  count_0  count_1
0  (0.0, 0.5]        1        1
1  (0.5, 1.0]        1        2
2  (8.0, 8.5]        0        1

One option is to use cut + crosstab:

out = (pd.crosstab(pd.cut(df['SED'], np.arange(int(df['SED'].min()), int(df['SED'].max())+1, 0.5)), df['f'])
       .add_prefix('count_').rename_axis(index='SED_bins').reset_index())

Output:

f    SED_bins  count_0  count_1
0  (0.0, 0.5]        1        1
1  (0.5, 1.0]        1        2
2  (8.0, 8.5]        0        1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文