首页 > 解决方案 > pandas python中的等价物

问题描述

我想在 python 中执行下面的函数,最好使用 pandas 作为我的数据聚合过程的一部分。在 tidyverse 中有一个不错的函数across,它与starts_with函数相结合,是一个非常强大的组合。

library(tidyverse)

df <- tibble(mtcars)

aggregate <- function(...) {
  df %>% 
    group_by(...) %>% 
    summarise(across(ends_with("p"), ~ weighted.mean(.x, w = am))) %>% 
    ungroup()
}

res1 <- aggregate(gear)
res2 <- aggregate(cyl)

标签: pythonrpandastidyverse

解决方案


在python中检查数据包。

有了它,您将能够以 tidyverse 的方式轻松地操作您的数据:

from datar.all import f, group_by, summarise, ungroup, across, ends_with, weighted_mean
from datar.datasets import mtcars as df

def aggregate (*gvars):
  return df >> group_by(*gvars) >> summarise(
    across(ends_with("p"), weighted_mean, w=f.am)
  ) >> ungroup()

res1 = aggregate(f.gear)
#    gear      disp       hp
# 0     3       NaN      NaN
# 1     4  106.6875   83.875
# 2     5  202.4800  195.600

res2 = aggregate(f.cyl)
#   cyl      disp          hp
# 0    4   93.6125   81.875000
# 1    6  155.0000  131.666667
# 2    8  326.0000  299.500000

我是包的作者。如果您在使用过程中有任何问题,请随时提交问题。


推荐阅读