Search code examples
pythonpython-polarsduckdb

"horizontal sum" in DuckDB?


In Polars I can do:

import polars as pl
df = pl.DataFrame({'a': [1,2,3], 'b': [4, 5, 6]})
df.select(pl.sum_horizontal('a', 'b'))

shape: (3, 1)
┌─────┐
│ a   │
│ --- │
│ i64 │
╞═════╡
│ 5   │
│ 7   │
│ 9   │
└─────┘

Is there a way to do this with DuckDB?


Solution

  • COLUMNS() can now be unpacked as of DuckDB 1.1.0

    This does allow you to use the list_* functions e.g.

    duckdb.sql("""
    from df 
    select list_sum(list_value(*columns(*)))
    """)
    
    ┌──────────────────────────────────┐
    │ list_sum(list_value(df.a, df.b)) │
    │              int128              │
    ├──────────────────────────────────┤
    │                                5 │
    │                                7 │
    │                                9 │
    └──────────────────────────────────┘