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

在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 17:02:37