如何在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))
最终结果
处理后的数据如下:
| State | cancer | lifexp | health | cancernew | lifeexpnew | healthnew |
|---|---|---|---|---|---|---|
| NSW | 0.003 | 81 | 95 | 1 | 2 | 3 |
| VIC | 0.005 | 85 | 95 | 2 | 3 | 3 |
| QLD | 0.003 | 81 | 93 | 1 | 2 | 2 |
| WA | 0.005 | 84 | 95 | 2 | 3 | 3 |
| SA | 0.004 | 83 | 92 | 2 | 2 | 2 |
| TAS | 0.002 | 80 | 91 | 1 | 1 | 1 |
| ACT | 0.005 | 82 | 89 | 2 | 2 | 1 |
| NT | 0.006 | 79 | 93 | 2 | 1 | 2 |
内容的提问来源于stack exchange,提问作者user20825888
相关产品推荐
相关产品推荐

