Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(python): Fix fill null types #19656

Merged
merged 1 commit into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions py-polars/polars/lazyframe/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -5667,15 +5667,15 @@ def fill_null(
│ 4 ┆ 13.0 │
└─────┴──────┘
"""
dtypes: Sequence[PolarsDataType]
dtypes: Sequence[PolarsDataType] | None

if value is not None:

def infer_dtype(value: Any) -> PolarsDataType:
return next(iter(self.select(value).collect_schema().values()))

if isinstance(value, pl.Expr):
dtypes = [infer_dtype(value)]
dtypes = None
elif isinstance(value, bool):
dtypes = [Boolean]
elif matches_supertype and isinstance(value, (int, float)):
Expand Down Expand Up @@ -5707,9 +5707,12 @@ def infer_dtype(value: Any) -> PolarsDataType:
dtypes = [String, Categorical]
else:
# fallback; anything not explicitly handled above
dtypes = [infer_dtype(F.lit(value))]
dtypes = None

return self.with_columns(F.col(dtypes).fill_null(value, strategy, limit))
if dtypes:
return self.with_columns(
F.col(dtypes).fill_null(value, strategy, limit)
)

return self.select(F.all().fill_null(value, strategy, limit))

Expand Down
14 changes: 14 additions & 0 deletions py-polars/tests/unit/operations/test_fill_null.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,17 @@ def test_fill_null_f32_with_lit() -> None:
# ensure the literal integer does not upcast the f32 to an f64
df = pl.DataFrame({"a": [1.1, 1.2]}, schema=[("a", pl.Float32)])
assert df.fill_null(value=0).dtypes == [pl.Float32]


def test_fill_null_lit_() -> None:
df = pl.DataFrame(
{
"a": pl.Series([1, None], dtype=pl.Int32),
"b": pl.Series([None, 2], dtype=pl.UInt32),
"c": pl.Series([None, 2], dtype=pl.Int64),
}
)
assert (
df.fill_null(pl.lit(0)).select(pl.all().null_count()).transpose().sum().item()
== 0
)