Skip to content

Commit

Permalink
fix(rust, python): don't cast nulls before trying normal cast (#6339)
Browse files Browse the repository at this point in the history
  • Loading branch information
ritchie46 authored Jan 20, 2023
1 parent dbd2f13 commit fde2682
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
15 changes: 10 additions & 5 deletions polars/polars-core/src/series/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,11 +228,16 @@ impl Series {

/// Cast `[Series]` to another `[DataType]`
pub fn cast(&self, dtype: &DataType) -> PolarsResult<Self> {
let len = self.len();
if self.null_count() == len {
Ok(Series::full_null(self.name(), len, dtype))
} else {
self.0.cast(dtype)
match self.0.cast(dtype) {
Ok(out) => Ok(out),
Err(err) => {
let len = self.len();
if self.null_count() == len {
Ok(Series::full_null(self.name(), len, dtype))
} else {
Err(err)
}
}
}
}

Expand Down
29 changes: 29 additions & 0 deletions py-polars/tests/unit/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -626,3 +626,32 @@ def test_nested_read_dict_4143() -> None:
],
],
}


@typing.no_type_check
def test_from_records_nullable_structs() -> None:
records = [
{"id": 1, "items": [{"item_id": 100, "description": None}]},
{"id": 1, "items": [{"item_id": 100, "description": "hi"}]},
]

schema = [
("id", pl.UInt16),
(
"items",
pl.List(
pl.Struct(
[pl.Field("item_id", pl.UInt32), pl.Field("description", pl.Utf8)]
)
),
),
]

for columns in [schema, None]:
assert pl.DataFrame(records, orient="row", columns=columns).to_dict(False) == {
"id": [1, 1],
"items": [
[{"item_id": 100, "description": None}],
[{"item_id": 100, "description": "hi"}],
],
}

0 comments on commit fde2682

Please sign in to comment.