在R Studio中为Health数据框按年龄条件新增Stage of Life列
给Health数据框新增「Stage of Life」列的实现方案
核心需求
为已存在的Health数据框新增一列Stage of Life,规则为:
- 年龄大于37 → 标记为
older - 年龄小于37 → 标记为
Younger
实现方法(以Python Pandas为例)
方法1:使用numpy.where快速判断
import numpy as np import pandas as pd # 替换'Age'为数据框中实际的年龄列名 Health['Stage of Life'] = np.where(Health['Age'] > 37, 'older', 'Younger')
方法2:使用pd.cut分箱处理
适合后续需要扩展多阶段划分的场景:
Health['Stage of Life'] = pd.cut( Health['Age'], bins=[-float('inf'), 37, float('inf')], labels=['Younger', 'older'], include_lowest=True )
注意事项
- 确保年龄列是数值类型(
int/float),若为字符串需先转换:Health['Age'] = pd.to_numeric(Health['Age'], errors='coerce') - 当前规则未明确年龄等于37的情况,上述代码会将等于37的标记为
Younger,若需调整可修改条件(如将>37改为>=37)
内容的提问来源于stack exchange,提问作者ellen
相关产品推荐
相关产品推荐

