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

如何将pandas.cut的区间左边界设为输出标签?

提取pd.cut区间左边界作为bin列数值

问题描述

现有如下DataFrame:

import pandas as pd
df = pd.DataFrame(
    {
        'high': [110, 110, 101, 101, 115, 300],
    }
)

期望生成包含bin列的输出,其中bin值为对应区间的左边界:

high  bin
0   110  105.0
1   110  105.0
2   101  100.0
3   101  100.0
4   115  111.0
5   300  220.0

使用pd.cut尝试生成bin列,但返回的是区间类别而非左边界数值:

import numpy as np    
evaluation_bins = [100, 105, 111, 120, 220, np.inf]    
df['bin'] = pd.cut(df['high'], bins=evaluation_bins, include_lowest=True, right=False)

解决方案

pd.cut返回的IntervalArray类型对象,每个元素的left属性即为区间左边界,直接提取即可:

方法1:向量化提取(推荐,效率更高)

直接访问pd.cut结果的.left属性,一步生成目标列:

import numpy as np    
evaluation_bins = [100, 105, 111, 120, 220, np.inf]    
df['bin'] = pd.cut(df['high'], bins=evaluation_bins, include_lowest=True, right=False).left

方法2:apply遍历提取

适合需要额外处理区间的场景:

import numpy as np    
evaluation_bins = [100, 105, 111, 120, 220, np.inf]    
# 先生成区间列
df['bin_interval'] = pd.cut(df['high'], bins=evaluation_bins, include_lowest=True, right=False)
# 提取左边界
df['bin'] = df['bin_interval'].apply(lambda x: x.left)
# 可选:删除中间区间列
df.drop('bin_interval', axis=1, inplace=True)

执行后即可得到期望的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 18:02:10