You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按数值区间分类DataFrame数据并统计各Type数量?

问题描述

现有如下结构的DataFrame:

Index   Type    Value
0       A       4
1       A       9
2       C       51
3       B       40
4       C       32
5       C       14

需要将数据按0-10、11-50、51-100的数值区间分类,生成新的DataFrame,展示每个区间下各Type的数量,预期输出如下:

Class   A   B   C
0-10    2   0   0
11-50   0   1   2
51-100  0   0   1
解决方案

可以通过Pandas的区间划分与交叉统计功能实现需求,具体步骤如下:

1. 导入库并构建原始DataFrame

import pandas as pd

# 构建原始数据
df = pd.DataFrame({
    'Type': ['A', 'A', 'C', 'B', 'C', 'C'],
    'Value': [4, 9, 51, 40, 32, 14]
})

2. 按指定区间划分数据

使用pd.cut()将Value列映射到目标区间,并新增Class列存储分组结果:

# 定义区间边界和对应标签
bins = [0, 10, 50, 100]
labels = ['0-10', '11-50', '51-100']

# 生成区间分组列
df['Class'] = pd.cut(df['Value'], bins=bins, labels=labels, include_lowest=True)

注:include_lowest=True确保最小值(如0)能被正确纳入第一个区间,保证逻辑严谨性

3. 生成区间-类型的数量统计表格

用pd.crosstab()生成交叉统计表格,补全缺失值并调整格式:

# 生成交叉统计表,补全0值并转为整数类型
result = pd.crosstab(df['Class'], df['Type']).fillna(0).astype(int)

# 将索引转为列,匹配预期输出格式
result = result.reset_index()

执行上述代码后,result即为符合要求的DataFrame,输出结果与预期完全一致。

内容的提问来源于stack exchange,提问作者Aukru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 00:20:31