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

Python中基于Spread列多条件为DataFrame创建新列

基于Spread列条件创建New_Column的实现方案

针对你需要按区间规则生成新列的需求,推荐使用pd.cut或np.select来实现,比嵌套where更简洁直观,以下是具体代码:

方法一:使用pd.cut(适配区间分段场景)

import pandas as pd

# 构造示例数据
df = pd.DataFrame({'Spread': [1, 2, 5, 6, 9, 11, 13]})

# 定义区间边界与对应结果
bins = [-float('inf'), 4, 8, 12, float('inf')]
labels = [4, 8, 12, 16]

# 生成新列,include_lowest=True确保<=4的区间包含左边界
df['New_Column'] = pd.cut(df['Spread'], bins=bins, labels=labels, include_lowest=True)
# 转换为整数类型(可选,pd.cut默认返回分类类型)
df['New_Column'] = df['New_Column'].astype(int)

方法二:使用np.select(适配自定义多条件场景)

import pandas as pd
import numpy as np

df = pd.DataFrame({'Spread': [1, 2, 5, 6, 9, 11, 13]})

# 定义条件列表和对应结果值
conditions = [
    df['Spread'] <= 4,
    (df['Spread'] > 4) & (df['Spread'] <= 8),
    (df['Spread'] > 8) & (df['Spread'] <= 12),
    df['Spread'] > 12
]
values = [4, 8, 12, 16]

# 生成新列
df['New_Column'] = np.select(conditions, values)

两种方法执行后,都会得到你期望的结果:

SpreadNew_Column
14
24
58
68
912
1112
1316

注:where方法更适合单条件替换逻辑,多区间判断时嵌套写法冗余,上述两种方法更适配你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:35:12