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)
两种方法执行后,都会得到你期望的结果:
| Spread | New_Column |
|---|---|
| 1 | 4 |
| 2 | 4 |
| 5 | 8 |
| 6 | 8 |
| 9 | 12 |
| 11 | 12 |
| 13 | 16 |
注:where方法更适合单条件替换逻辑,多区间判断时嵌套写法冗余,上述两种方法更适配你的需求。
内容的提问来源于stack exchange,提问作者Jay
相关产品推荐
相关产品推荐

