Search code examples
pythonlistpython-polarselementwise-operations

Polars - How to add two series that contain lists as elements


Trying to add, subtract, two Series that contains datatype List[i64]. The operation seems to be not supported.

a = pl.Series("a",[[1,2],[2,3]])
b = pl.Series("b",[[4,5],[6,7]])
c = a+b

this gives the error:

PanicException: `add` operation not supported for dtype `list[i64]`

I would expect a element-wise sum, like would happen with numpy array for example:

c = [[5,7],[8,10]]

What's the correct syntax to add two series of lists?


Solution

  • you can do the following:

    
    c = (a.explode() + b.explode()).reshape((2,-1)).alias('c')
    
    shape: (2,)
    Series: 'a' [list[i64]]
    [
        [5, 7]
        [8, 10]
    ]
    

    Final thoughts: if your list has a fixed size, then you might consider using the new Polars Array datatype.