Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace certain values in a Polars Series?

I want to replace the inf values in a polars series with 0. I am using the polars Python library.

This is my example code:

import polars as pl

example = pl.Series([1,2,float('inf'),4])


This is my desired output:

output = pl.Series([1.0,2.0,0.0,4.0])

All similiar questions regarding replacements are regarding polars Dataframes using the .when expression (e.g Replace value by null in Polars) which does not seem to be available in a Series object:

AttributeError: 'Series' object has no attribute 'when'

Is this possible using polars expressions?

EDIT: I found the following solution but it seems very convoluted:

example.map_dict({float('inf'): 0 }, default= pl.first())
like image 431
Sandwichnick Avatar asked Oct 11 '25 12:10

Sandwichnick


1 Answers

import polars as pl

example = pl.Series("example", [1, 2, float('inf'), 4])

# Create a DataFrame from the Series
df = pl.DataFrame([example])

# Replace inf values with 0 using the when expression
df = df.with_columns(
    pl.when(pl.col("example") == float('inf'))
    .then(0)
    .otherwise(pl.col("example"))
    .alias("example")
)

# Get the output Series
output = df["example"]

print(output)

Result:

shape: (4,)
Series: 'example' [f64]
[
    1.0
    2.0
    0.0
    4.0
]
like image 94
Taras Drapalyuk Avatar answered Oct 15 '25 19:10

Taras Drapalyuk