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

如何在Python中基于现有列值创建新列?附数据集示例

实现Pandas数据区间分箱并创建新列

1. 导入依赖并构建数据集

import pandas as pd
import numpy as np

# 构建目标数据集
data = {
    'State': ['NSW', 'VIC', 'QLD', 'WA', 'SA', 'TAS', 'ACT', 'NT'],
    'cancer': [0.003, 0.005, 0.003, 0.005, 0.004, 0.002, 0.005, 0.006],
    'lifexp': [81, 85, 81, 84, 83, 80, 82, 79],
    'health': [95, 95, 93, 95, 92, 91, 89, 93]
}
df = pd.DataFrame(data)

2. 创建cancernew列

按照规则:值小于0.004时为1,0.004至0.006之间为2,大于0.006时为3:

df['cancernew'] = np.where(df['cancer'] < 0.004, 1,
                          np.where(df['cancer'] <= 0.006, 2, 3))

3. 创建lifeexpnew列

按照规则:值小于81时为1,81至83之间为2,大于83时为3:

df['lifeexpnew'] = np.where(df['lifexp'] < 81, 1,
                           np.where(df['lifexp'] <= 83, 2, 3))

4. 创建healthnew列

按照规则:值小于92时为1,92至94之间为2,大于94时为3:

df['healthnew'] = np.where(df['health'] < 92, 1,
                          np.where(df['health'] <= 94, 2, 3))

最终结果

处理后的数据如下:

Statecancerlifexphealthcancernewlifeexpnewhealthnew
NSW0.0038195123
VIC0.0058595233
QLD0.0038193122
WA0.0058495233
SA0.0048392222
TAS0.0028091111
ACT0.0058289221
NT0.0067993212

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 13:07:52