[Python] Polars group_by + describe: return all columns as single dataframe

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

  1. Stack

    Stack Membro Participativo

    I'm slowly migrating to polars from pandas and I have found that in some cases the polars syntax is tricky.

    I'm seeking help to do a group_by followed by a describe using less (or more readable) code.

    See this example:

    from io import BytesIO
    import pandas as pd
    import polars as pl

    S = b'''group,value\n3,245\n3,28\n3,48\n1,113\n1,288\n1,165\n2,90\n2,21\n2,109'''

    pl_df = pl.read_csv(BytesIO(S))
    pd_df = pd.read_csv(BytesIO(S))

    # Polars' way
    pl_df.group_by('group').map_groups(
    lambda df: (
    df['value']
    .describe()
    .with_columns(
    group=pl.lit(df['group'][0])
    )
    )
    ).pivot(index='group', on='statistic')


    Something similar in pandas would be:

    # pandas'
    pd_df.groupby('group').value.describe()

    Continue reading...

Compartilhe esta Página