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

R语言根据Yr、Month两列缺失值规则计算Age列的高效实现方法

简洁实现方案

以下是R和Python两种常用数据处理语言的实现,均为向量化运算,执行效率远高于逐行循环判断,代码量远低于30行:

R 实现

推荐使用dplyr包的函数实现,逻辑清晰可读性强:

library(dplyr)

# 仅需1行核心代码即可完成Age列计算,默认保留2位小数匹配需求
df <- df %>%
  mutate(Age = round(ifelse(is.na(Yr) & is.na(Month), NA_real_, coalesce(Yr, 0) + coalesce(Month/12, 0)), 2))

说明:coalesce函数会把传入的空值替换为指定的0,两个字段都为空的场景单独判断返回NA,完全符合你给出的4种计算规则。你也可以用case_when做更直观的条件匹配:

df <- df %>%
  mutate(Age = round(case_when(
    is.na(Month) ~ Yr,
    is.na(Yr) ~ Month / 12,
    TRUE ~ Yr + Month / 12
  ), 2))

Python 实现

使用pandas+numpy的向量化操作实现:

import pandas as pd
import numpy as np

df['Age'] = round(np.where(
    df['Yr'].isna() & df['Month'].isna(),
    np.nan,
    df['Yr'].fillna(0) + df['Month'].fillna(0)/12
), 2)

说明:fillna(0)将空值替换为0,两个字段都为空的场景单独返回NaN,完全匹配计算规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:18:03