How to convert data in Polars?

15.1k views Asked by At

I used .write_ipc from Polars to store as a feather file. It turns out that the numerical strings have been saved as integers.

So I need to convert the columns with integers to strings either before saving as feather or after reading from feather. How do I do that with Polars?

1

There are 1 answers

1
ritchie46 On

Are you sure? This snippets succeeds so that means data types are preserved.

import polars as pl
import io

df = pl.DataFrame({
    "numeric_strs": ["1", "2", "3"],
    "numeric ints": [1, 2, 3]
})

f = io.BytesIO()
df.write_ipc(f)
f.seek(0)

assert pl.read_ipc(f).dtypes == [pl.Utf8, pl.Int64]

To answer your question you can cast polars data types:

# cast to a string column
df.with_column(pl.col("numeric_ints").cast(pl.Utf8))