[Python] Groupby sum string

Discussão em 'Python' iniciado por Stack, Outubro 6, 2024.

  1. Stack

    Stack Membro Participativo

    In pandas, I can do

    In [33]: df = pd.DataFrame({'a': [1, 1, 2], 'b': ['foo', 'bar', 'foo']})

    In [34]: df
    Out[34]:
    a b
    0 1 foo
    1 1 bar
    2 2 foo

    In [35]: df.groupby('a')['b'].sum()
    Out[35]:
    a
    1 foobar
    2 foo
    Name: b, dtype: object


    and have the strings concatenated when I do groupby.sum

    In polars, however:

    In [36]: df = pl.DataFrame({'a': [1, 1, 2], 'b': ['foo', 'bar', 'foo']})

    In [37]: df
    Out[37]:
    shape: (3, 2)
    ┌─────┬─────┐
    │ a ┆ b │
    │ --- ┆ --- │
    │ i64 ┆ str │
    ╞═════╪═════╡
    │ 1 ┆ foo │
    │ 1 ┆ bar │
    │ 2 ┆ foo │
    └─────┴─────┘

    In [38]: df.group_by('a').agg(pl.col('b').sum())
    Out[38]:
    shape: (2, 2)
    ┌─────┬──────┐
    │ a ┆ b │
    │ --- ┆ --- │
    │ i64 ┆ str │
    ╞═════╪══════╡
    │ 2 ┆ null │
    │ 1 ┆ null │
    └─────┴──────┘


    Is there a way to concatenate all the strings in each group in polars?

    Continue reading...

Compartilhe esta Página