[Python] Expand Columns of Structs to Rows in polars

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

  1. Stack

    Stack Membro Participativo

    Say we have this dataframe:

    import polars as pl
    df = pl.DataFrame({'EU': {'size': 10, 'GDP': 80},
    'US': {'size': 100, 'GDP': 800},
    'AS': {'size': 80, 'GDP': 500}})

    shape: (1, 3)
    ┌───────────┬───────────┬───────────┐
    │ EU ┆ US ┆ AS │
    │ --- ┆ --- ┆ --- │
    │ struct[2] ┆ struct[2] ┆ struct[2] │
    ╞═══════════╪═══════════╪═══════════╡
    │ {10,80} ┆ {100,800} ┆ {80,500} │
    └───────────┴───────────┴───────────┘


    I am looking for a function like df.expand_structs(column_name='metric') that gives

    shape: (2, 4)
    ┌────────┬─────┬─────┬─────┐
    │ metric ┆ EU ┆ US ┆ AS │
    │ --- ┆ --- ┆ --- ┆ --- │
    │ str ┆ i64 ┆ i64 ┆ i64 │
    ╞════════╪═════╪═════╪═════╡
    │ size ┆ 10 ┆ 100 ┆ 80 │
    │ GBP ┆ 80 ┆ 800 ┆ 500 │
    └────────┴─────┴─────┴─────┘


    I've tried other functions like unnest, explode but no luck. Any help appreciated!

    Continue reading...

Compartilhe esta Página