Search code examples
pythonpython-polars

Polars convert string of digits to list


So i have a polars column/series that is strings of digits.

s = pl.Series("a", ["111","123","101"])
s
shape: (3,)
Series: 'a' [str]
[
    "111"
    "123"
    "101"
]

I would like to convert each string into a list of integers. I have found a working solution but i am not sure if it is optimal.

s.str.split("").list.eval(pl.element().str.to_integer(base=10))

shape: (3,)
Series: 'a' [list[i32]]
[
    [1, 1, 1]
    [1, 2, 3]
    [1, 0, 1]
]

This seems to be working but id like to know if there are better ways to do this or any of the individual steps.


Solution

  • Update: .str.split("") no longers inserts leading/trailing empty strings in the result.

    So you can just .cast() the resulting list directly.

    s.str.split("").cast(pl.List(pl.Int64))
    
    shape: (3,)
    Series: 'a' [list[i64]]
    [
        [1, 1, 1]
        [1, 2, 3]
        [1, 0, 1]
    ]