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

在Google Colab中使用rpy2获取R数据框变量的计数与占比方法

在rpy2(Google Colab)中获取数据框各变量的计数与占比

单个变量的计数与占比

R中没有和Python df.value_counts() 完全等价的单函数,但可以通过 table() + prop.table() 组合实现,结合rpy2的调用方式如下:

  1. 先将Python DataFrame转为R数据框(假设你已有Python的df):
from rpy2.robjects import pandas2ri, r
pandas2ri.activate()  # 启用pandas与R数据结构互转
r_df = pandas2ri.py2rpy(df)
  1. 获取单个变量的计数:
# 替换var_name为你的目标变量名
counts = r['table'](r_df.rx2('var_name'))
print(counts)
  1. 获取单个变量的计数+占比:
    定义R函数整合结果,方便查看:
# 定义R处理函数
r("""
get_var_counts_props <- function(df, var) {
  tbl <- table(df[[var]])
  props <- prop.table(tbl)
  res <- data.frame(
    Category = names(tbl),
    Count = as.numeric(tbl),
    Proportion = round(as.numeric(props), 4)  # 保留4位小数
  )
  return(res)
}
""")

# 调用函数并转回Python DataFrame
result = r['get_var_counts_props'](r_df, 'var_name')
pandas2ri.rpy2py(result)

批量处理所有变量

如果要一次性获取数据框中所有变量的计数与占比,用lapply遍历所有列批量生成结果:

# 定义批量处理的R函数
r("""
get_all_vars_counts_props <- function(df) {
  res_list <- lapply(names(df), function(var) {
    tbl <- table(df[[var]])
    props <- prop.table(tbl)
    data.frame(
      Category = names(tbl),
      Count = as.numeric(tbl),
      Proportion = round(as.numeric(props), 4),
      Variable = var  # 标记所属变量
    )
  })
  # 合并所有结果为单个数据框(也可保留列表形式)
  do.call(rbind, res_list)
}
""")

# 调用批量函数并转回Python格式
all_result = r['get_all_vars_counts_props'](r_df)
pandas2ri.rpy2py(all_result)

用dplyr实现tidy风格的处理

如果习惯tidyverse语法,用dplyr可以写出更简洁的代码:

# 加载dplyr包
r("library(dplyr)")

# 定义dplyr版本的批量函数
r("""
get_counts_props_dplyr <- function(df) {
  purrr::map_dfr(names(df), function(var) {
    df %>%
      count({{sym(var)}}) %>%
      mutate(
        Proportion = round(n / sum(n), 4),
        Variable = var
      ) %>%
      rename(Category = {{sym(var)}})
  })
}
""")

# 调用函数并转回Python DataFrame
dplyr_result = r['get_counts_props_dplyr'](r_df)
pandas2ri.rpy2py(dplyr_result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 01:03:14