python - 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)
解决方案
在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
我是包的作者。如果您在使用过程中有任何问题,请随时提交问题。
推荐阅读
- javascript - 通过 axios 导入 Vue 组件并更新内容
- c# - C# oledb 查询值和目标字段的个数不一样
- awk - awk if/else 抛出错误
- php - 获取使用 ldap 进行 SSO 登录 windows 的用户
- linux - 如何在 linux 中解压 .vw.gz 文件?
- apache-spark - 为什么在 hadoop 上使用 H2O 时看不到 Yarn 中的特定任务执行?
- javascript - Angular js将字符串属性转换为json对象内的布尔值
- javascript - Meteor 1.6 在客户端和服务器端进行同步调用
- python - Google Flex App Engine 未写入 Cloud SQL 数据库
- python - 从未调用 Django m2m_changed 信号