From d3f8a5c7f637c06f5cb3d97fd76af7e6a34ee399 Mon Sep 17 00:00:00 2001 From: Gijs Burghoorn Date: Tue, 24 Sep 2024 14:03:29 +0200 Subject: [PATCH] fix: Properly cast AnyValue string (#18888) --- crates/polars-core/src/datatypes/any_value.rs | 5 +++++ crates/polars-python/src/dataframe/export.rs | 6 +++--- py-polars/tests/unit/test_convert.py | 4 ++++ 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/polars-core/src/datatypes/any_value.rs b/crates/polars-core/src/datatypes/any_value.rs index fa8bf7caa3a1..83d9d4f8301d 100644 --- a/crates/polars-core/src/datatypes/any_value.rs +++ b/crates/polars-core/src/datatypes/any_value.rs @@ -563,6 +563,11 @@ impl<'a> AnyValue<'a> { (AnyValue::Float64(v), DataType::Boolean) => AnyValue::Boolean(*v != f64::default()), // to string + (AnyValue::String(v), DataType::String) => { + AnyValue::StringOwned(PlSmallStr::from_str(v)) + }, + (AnyValue::StringOwned(v), DataType::String) => AnyValue::StringOwned(v.clone()), + (av, DataType::String) => { if av.is_unsigned_integer() { AnyValue::StringOwned(format_pl_smallstr!("{}", av.extract::()?)) diff --git a/crates/polars-python/src/dataframe/export.rs b/crates/polars-python/src/dataframe/export.rs index cfd6feaa0138..c9fe0d4a48d0 100644 --- a/crates/polars-python/src/dataframe/export.rs +++ b/crates/polars-python/src/dataframe/export.rs @@ -49,15 +49,15 @@ impl PyDataFrame { (0..df.height()).map(|idx| { PyTuple::new_bound( py, - self.df.get_columns().iter().map(|s| match s.dtype() { + self.df.get_columns().iter().map(|c| match c.dtype() { DataType::Null => py.None(), DataType::Object(_, _) => { let obj: Option<&ObjectValue> = - s.get_object(idx).map(|any| any.into()); + c.get_object(idx).map(|any| any.into()); obj.to_object(py) }, // SAFETY: we are in bounds. - _ => unsafe { Wrap(s.get_unchecked(idx)).into_py(py) }, + _ => unsafe { Wrap(c.get_unchecked(idx)).into_py(py) }, }), ) }), diff --git a/py-polars/tests/unit/test_convert.py b/py-polars/tests/unit/test_convert.py index 0258ded0d18d..123c0a0cdebe 100644 --- a/py-polars/tests/unit/test_convert.py +++ b/py-polars/tests/unit/test_convert.py @@ -46,3 +46,7 @@ def test_from_dicts_all_cols_6716() -> None: ): pl.from_dicts(dicts, infer_schema_length=20) assert pl.from_dicts(dicts, infer_schema_length=None).dtypes == [pl.String] + + +def test_dict_float_string_roundtrip_18882() -> None: + assert pl.from_dicts([{"A": "0.1"}]).to_dicts() == [{"A": "0.1"}]