[Python] python/pandas equivalent to dplyr 1.0.0 summarize(across())

Discussão em 'Python' iniciado por Stack, Março 6, 2025.

  1. Stack

    Stack Membro Participativo

    In R, I find the following very useful when dealing with many variables:

    library(dplyr)
    dat <- group_by(mtcars, cyl)
    summarize(dat, across(c('mpg','disp'), sum), across(c('drat','wt','qsec'), mean))
    # A tibble: 3 x 5
    cyl disp hp drat wt
    <dbl> <dbl> <dbl> <dbl> <dbl>
    1 4 1156. 909 4.07 2.29
    2 6 1283. 856 3.59 3.12
    3 8 4943. 2929 3.23 4.00


    Or even better, selecting with pseudo-regex

    summarize(dat, across(ends_with('p'), sum), across(ends_with('t'), mean))


    In pandas, the equivalent seems to pass variables one-by-one into a dictionary, eg from this gist:

    group_agg = df.groupby("group1").agg({
    "var1" : ["mean"],
    "var2" : ["sum"],
    "var3" : ["mean"]
    })


    Is there a less verbose way to do this operation in pandas, or with some other package?

    Continue reading...

Compartilhe esta Página