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

如何在Python中将Pandas区间类型数据替换为整数?

pd.cut分箱后区间转整数编码的可行方案

用pd.cut对年龄数据分箱得到区间类型的age_bands列后,想将区间映射为对应整数(如(0,10]→0、(10,20]→1),直接用replace方法(以字符串为键)会失败——因为age_bands的元素是Interval对象而非字符串,无法匹配。以下是几种可行实现方案:

方案一:生成分箱时直接指定labels(推荐)

在调用pd.cut时,直接通过labels参数传入对应整数列表,一步生成编码列,无需后续处理:

import pandas as pd 
df = pd.DataFrame()
df['age'] = [43, 76, 27, 8, 57, 32, 12, 22]
age_band = [0,10,20,30,40,50,60,70,80,90]

# 同时生成区间列和编码列
df['age_bands'] = pd.cut(df['age'], bins=age_band, ordered=True)
df['age_code'] = pd.cut(df['age'], bins=age_band, ordered=True, labels=list(range(len(age_band)-1)))

说明:len(age_band)-1对应分箱后的区间总数,labels用0到n-1的整数列表,刚好匹配每个区间的顺序编码。

方案二:利用Categorical类型的cat.codes属性

pd.cut返回的是Categorical类型列,自带cat.codes属性,直接提取即可得到与区间顺序一致的编码:

# 基于已生成的age_bands列
df['age_code'] = df['age_bands'].cat.codes

说明:这种方法最简洁,无需手动维护映射关系,编码顺序严格遵循分箱区间的排序(与ordered=True设置一致)。

方案三:手动自定义映射(按需使用)

如果需要自定义编码(而非按区间顺序),需使用Interval对象作为映射的键(而非字符串):

# 定义区间到编码的映射(键为Interval对象,closed参数要和pd.cut一致)
interval_map = {
    pd.Interval(0, 10, closed='right'): 0,
    pd.Interval(10, 20, closed='right'): 1,
    pd.Interval(20, 30, closed='right'): 2,
    pd.Interval(30, 40, closed='right'): 3,
    pd.Interval(40, 50, closed='right'): 4,
    pd.Interval(50, 60, closed='right'): 5,
    pd.Interval(60, 70, closed='right'): 6,
    pd.Interval(70, 80, closed='right'): 7,
    pd.Interval(80, 90, closed='right'): 8
}

# 使用map方法完成映射
df['age_code'] = df['age_bands'].map(interval_map)

说明:之前用字符串'(40, 50]'作为键失败,是因为age_bands中的元素是Interval对象,而非字符串,必须用同类型的Interval对象作为键才能匹配成功。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 07:48:43