A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: sanitize nan-infs for numeric cols only (#5036)
Shahmir Varqhadf58d03f056d
diff --git a/marimo/_plugins/ui/_impl/charts/altair_transformer.py b/marimo/_plugins/ui/_impl/charts/altair_transformer.pyindex 23b3cb313b..65e579b4aa 100644--- a/marimo/_plugins/ui/_impl/charts/altair_transformer.py+++ b/marimo/_plugins/ui/_impl/charts/altair_transformer.py@@ -152,14 +152,16 @@ def sanitize_nan_infs(data: Any) -> Any:"""Sanitize NaN and Inf values in Dataframes for JSON serialization."""if can_narwhalify(data):narwhals_data = nw.from_native(data)- res = narwhals_data.with_columns(- nw.when(nw.col(col).is_nan() | ~nw.col(col).is_finite())- .then(None)- .otherwise(nw.col(col))- .name.keep()- for col in narwhals_data.columns- )- return res.to_native()+ for col, dtype in narwhals_data.schema.items():+ # Only numeric columns can have NaN or Inf values+ if dtype.is_numeric():+ narwhals_data = narwhals_data.with_columns(+ nw.when(nw.col(col).is_nan() | ~nw.col(col).is_finite())+ .then(None)+ .otherwise(nw.col(col))+ .name.keep()+ )+ return narwhals_data.to_native()return datadiff --git a/tests/_output/formatters/test_altair_formatters.py b/tests/_output/formatters/test_altair_formatters.pyindex d819e4534c..3ffe3daf0a 100644--- a/tests/_output/formatters/test_altair_formatters.py+++ b/tests/_output/formatters/test_altair_formatters.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+from datetime import datetimefrom typing import TYPE_CHECKINGfrom unittest.mock import MagicMock, patch@@ -142,7 +143,18 @@ def test_altair_formatter_svg():@pytest.mark.parametrize("df",create_dataframes(- {"A": [1, 2, 3], "B": [-float("inf"), float("nan"), float("inf")]},+ {+ "A": [1, 2, 3],+ "B": [-float("inf"), float("nan"), float("inf")],+ "C": ["a", "b", "c"],+ "D": [1.0, 2.0, float("nan")],+ "E": [+ datetime(2020, 1, 1),+ datetime(2020, 1, 2),+ datetime(2020, 1, 3),+ ],+ "F": [None, None, None],+ },include=["polars", "pandas"],),)