R中如何基于其他列的特定条件创建新列:捕食者猎物数据处理
Python pandas 实现方案
首先定义猎物编码和数据列的映射关系:
import pandas as pd # 猎物编码与对应列名的映射 prey_map = {'SS': 'surf.smelt', 'SL': 'sandlance', 'H': 'herring'} col_to_prey = {v: k for k, v in prey_map.items()} prey_cols = list(prey_map.values())
新增OtherPrey?0/1标识列
逻辑是统计每行所有猎物列的丰度大于0的物种数,数量≥2则标记为1,否则为0:
df['OtherPrey?'] = (df[prey_cols].gt(0).sum(axis=1) >= 2).astype(int)
新增OtherAvailable列展示其他可用猎物
逐行判断除当前捕食的猎物外,还有哪些猎物的丰度大于0,返回对应缩写,无其他可用猎物则返回0:
def get_other(row): current_col = prey_map[row['Prey']] others = [col_to_prey[col] for col in prey_cols if col != current_col and row[col] > 0] return ','.join(others) if others else 0 df['OtherAvailable'] = df.apply(get_other, axis=1)
R 实现方案
依赖dplyr包处理:
library(dplyr) # 映射关系 prey_map <- c("SS" = "surf.smelt", "SL" = "sandlance", "H" = "herring") col_to_prey <- setNames(names(prey_map), prey_map) prey_cols <- unname(prey_map) # 新增目标列 df <- df %>% rowwise() %>% mutate( `OtherPrey?` = as.integer(sum(c_across(all_of(prey_cols)) > 0) >= 2), OtherAvailable = { current_col <- prey_map[Prey] valid_others <- prey_cols[prey_cols != current_col & c_across(all_of(prey_cols)) > 0] ifelse(length(valid_others) == 0, 0, paste(col_to_prey[valid_others], collapse = ",")) } ) %>% ungroup()
两种实现输出结果与需求完全匹配,多类其他猎物同时存在时会自动用逗号分隔拼接。
内容的提问来源于stack exchange,提问作者failedhighschool
相关产品推荐
相关产品推荐

