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

如何基于另一列值批量填充指定字符串?R与Python实现问询

R 高效批量映射方案

命名向量匹配(性能最优)

通过命名向量构建键值对映射,直接索引匹配Food列的值,是大数据集下最快的实现方式:

# 定义映射规则
food_type_map <- c(
  apple = "fruit", orange = "fruit", avocado = "fruit",
  beef = "meat", chicken = "meat",
  tomato = "vegetable", spinach = "vegetable", lettuce = "vegetable"
)

# 生成Type列
dataset$Type <- food_type_map[dataset$Food]
# 可选:处理未匹配的默认值
dataset$Type[is.na(dataset$Type)] <- "unknown"

dplyr::case_match(可读性优先)

如果需要清晰展示匹配逻辑,使用dplyr的case_match函数,比嵌套ifelse效率高,代码更易维护:

library(dplyr)
dataset <- dataset %>%
  mutate(Type = case_match(
    Food,
    c("apple", "orange", "avocado") ~ "fruit",
    c("beef", "chicken") ~ "meat",
    c("tomato", "spinach", "lettuce") ~ "vegetable",
    .default = "unknown" # 未匹配值的默认设置
  ))
Python 高效批量映射方案

pandas.map(常规高效方案)

构建映射字典后,用pandas的map方法批量转换,是处理此类映射的标准操作,速度快且代码简洁:

import pandas as pd

# 定义映射字典
food_type_map = {
    "apple": "fruit", "orange": "fruit", "avocado": "fruit",
    "beef": "meat", "chicken": "meat",
    "tomato": "vegetable", "spinach": "vegetable", "lettuce": "vegetable"
}

# 生成Type列
dataset["Type"] = dataset["Food"].map(food_type_map)
# 可选:填充未匹配的默认值
dataset["Type"] = dataset["Type"].fillna("unknown")

pandas.replace(灵活替代方案)

replace方法同样支持字典批量映射,和map效率接近,适合需要同时对多列进行值替换的场景:

dataset["Type"] = dataset["Food"].replace(food_type_map)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 12:17:52