1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] How to create a cross table in Python Polars?

Discussão em 'Python' iniciado por Stack, Setembro 17, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to count unique combinations in two Polars columns.

    In R


    df <- data.frame(a = c(2,0,1,0,0,0), b = c(1,1,1,0,0,1))
    table(df)
    0 1
    0 2 2
    1 0 1
    2 0 1

    In Pandas


    import numpy as np
    a = np.array([2,0,1,0,0,0])
    b = np.array([1,1,1,0,0,1])
    pd.crosstab(a, b)
    0 1
    0 2 2
    1 0 1
    2 0 1

    In Polars


    Is this the proper way?

    df = pl.DataFrame(
    {
    "a": [2,0,1,0,0,0],
    "b": [1,1,1,0,0,1]
    }
    )
    df.pivot(on="a", index="b", values="a", aggregate_function="len").fill_null(0)

    Continue reading...

Compartilhe esta Página