python pandas groupby复杂计算

Sla*_*vka 0 python pandas

我有df包含列的数据框:a, b, c, d。我想对数据进行分组a并进行一些计算。我将在 R 中提供这个计算的代码。我的主要问题是如何在 Pandas 中做同样的事情?

library(dplyr)
df %>%
    group_by(a) %>%
    summarise(mean_b = mean(b),
              qt95 = quantile(b, .95),
              diff_b_c = max(b-c),
              std_b_d = sd(b)-sd(d)) %>% 
    ungroup()
Run Code Online (Sandbox Code Playgroud)

这个例子是合成的,我只是想了解pandas的语法

jez*_*ael 5

我相信您需要自定义功能GroupBy.apply

def f(x):
    mean_b = x.b.mean()
    qt95 = x.b.quantile(.95)
    diff_b_c = (x.b - x.c).max()
    std_b_d = x.b.std() - x.d.std()
    cols = ['mean_b','qt95','diff_b_c','std_b_d']
    return pd.Series([mean_b, qt95, diff_b_c, std_b_d], index=cols)

df1 = df.groupby('a').apply(f)
Run Code Online (Sandbox Code Playgroud)