R vs Python Data Science Cheatsheet
前言:本文不定期更新,旨在为同时使用 R (Tidyverse) 和 Python (Pandas/NumPy) 的数据分析师提供快速语法对照。
注:R 示例主要基于
tidyverse风格;Python 示例主要基于pandas和numpy。
📊 核心语法对照表
| 功能分类 | R (Tidyverse/Base) | Python (Pandas/NumPy) |
|---|---|---|
| 基础访问 | ||
| 提取列 (变量) | data$v1data[["v1"]] | data.v1data["v1"] |
| 提取单列 (Series) | data[, "v1"] | data["v1"] |
| 提取多列 (DataFrame) | data[, c("v1", "v2")] | data[["v1", "v2"]] |
| 字符串操作 | ||
| 分割字符串 | str_split(string, pattern) | string.str.split(pat) |
| 检测包含 | str_detect(string, pattern) | string.str.contains(pat) |
| 字符串连接 | paste0(a, b)str_c(a, b) | a + bf"{a}{b}" |
| 替换字符串 | str_replace(string, pattern, replacement) | string.str.replace(pat, repl) |
| 数据筛选与排序 | ||
| 过滤行 | filter(data, condition) | data[data.condition]data.query("condition") |
| 复杂筛选示例 | df %>% filter(id %in% ids) %>% pull(photo_id) | df[df.id.isin(ids)].photo_id.tolist() |
| 排序 | arrange(data, desc(v1)) | data.sort_values("v1", ascending=False) |
| 去重 | distinct(data) | data.drop_duplicates() |
| 数据变形 (Reshape) | ||
| 长转宽 (Wide) | spread(key, value)pivot_wider() | pivot(index, columns, values) |
| 宽转长 (Long) | gather(key, value)pivot_longer() | melt()stack() |
| 分组聚合 | ||
| 分组计数 | tally()count(v1) | value_counts() |
| 分组聚合 | group_by(v1) %>% summarise(mean=mean(v2)) | groupby("v1")["v2"].mean() |
| 序列与形状 | ||
| 生成序列 | seq(from, to, by)1:10 | np.arange(start, stop, step) |
| 获取维度 | dim(data)nrow(data), ncol(data) | data.shapelen(data), len(data.columns) |
| 解包维度 | c(n, h, w) <- dim(array) | n, h, w = array.shape |
| 文件与路径 | ||
| 列出文件 | list.files(path) | os.listdir(path) |
| 路径拼接 | file.path(dir, filename)path.expand("~/data") | os.path.join(dir, filename)os.path.expanduser("~") |
| 读取 CSV | read_csv("file.csv") | pd.read_csv("file.csv") |
| 缺失值处理 | ||
| 判断缺失 | is.na(x) | pd.isna(x)x.isnull() |
| 填充缺失 | replace_na(list(v1=0)) | x.fillna(0) |
| 删除缺失 | drop_na() | x.dropna() |
| 绘图 (基础) | ||
| 散点图 | ggplot(data, aes(x, y)) + geom_point() | data.plot.scatter(x="x", y="y")plt.scatter(x, y) |
| 直方图 | geom_histogram() | data.hist()plt.hist(x) |
| 其他常用 | ||
| 管道操作符 | %>% | .pipe() (较少用,通常链式调用) |
| 条件赋值 | ifelse(cond, yes, no)case_when(...) | np.where(cond, yes, no)df.loc[cond, col] = val |
| 应用函数 | map_chr(vector, func)lapply(list, func) | [func(x) for x in list]list.map(func) |
💡 典型场景代码片段
1. 复杂数据筛选与提取
场景:从大表中筛选特定 ID 的照片 ID 列表。
R:
library(dplyr) expensive_photos <- train_photos %>% filter(business_id %in% expensive_businesses) %>% pull(photo_id) # 直接返回向量Python:
# 返回 List expensive_photos = train_photos[ train_photos['business_id'].isin(expensive_businesses) ]['photo_id'].tolist()
2. 图像数据维度解包
场景:处理类似 LFW (Labeled Faces in the Wild) 的图像数组。
R:
# 假设 images 是一个数组或列表结构 dims <- dim(lfw_people $ images) n_sample <- dims[1] h <- dims[2] w <- dims[3]Python:
# NumPy 风格解包 n_samples, h, w = lfw_people.images.shape
3. 批量构建文件路径
场景:遍历文件夹并构建完整路径列表。
R:
library(purrr) cat_dir <- "http://example.com/data" files <- list.files("local/path") full_paths <- map_chr(files, ~file.path(cat_dir, .x))Python:
import os cat_dir = "http://example.com/data" files = os.listdir("local/path") full_paths = [os.path.join(cat_dir, fn) for fn in files] # 或者使用 f-string (Python 3.6+) # full_paths = [f"{cat_dir}/{fn}" for fn in files]
4. 格式化输出
场景:动态生成字符串。
R:
# Base R sprintf("I'm %s. I'm %d years old.", "raindu", 26) # Glue package (推荐) glue::glue("I'm {name}. I'm {age} years old.", name="raindu", age=26)Python:
# Old style "I'm %s. I'm %d years old." % ("raindu", 26) # Format method "I'm {name}. I'm {age} years old.".format(name="raindu", age=26) # F-string (推荐, Python 3.6+) name, age = "raindu", 26 f"I'm {name}. I'm {age} years old."