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())
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
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With