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

Add support for arrays in lower and upper args of DataFrame.clip #982

Merged
merged 3 commits into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 2 additions & 2 deletions pandas-stubs/core/frame.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -1632,8 +1632,8 @@ class DataFrame(NDFrame, OpsMixin):
) -> DataFrame: ...
def clip(
self,
lower: float | None = ...,
upper: float | None = ...,
lower: float | AnyArrayLike | None = ...,
upper: float | AnyArrayLike | None = ...,
*,
axis: Axis | None = ...,
inplace: _bool = ...,
Expand Down
15 changes: 13 additions & 2 deletions tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,9 +527,20 @@ def test_types_quantile() -> None:
df.quantile(np.array([0.25, 0.75]))


def test_types_clip() -> None:
@pytest.mark.parametrize("lower", [None, 5, pd.Series([3, 4])])
@pytest.mark.parametrize("upper", [None, 15, pd.Series([12, 13])])
@pytest.mark.parametrize("axis", [None, 0, "index"])
def test_types_clip(lower, upper, axis) -> None:
def is_none_or_numeric(val: Any) -> bool:
return val is None or isinstance(val, int | float)

df = pd.DataFrame(data={"col1": [20, 12], "col2": [3, 14]})
df.clip(lower=5, upper=15)
uses_array = not (is_none_or_numeric(lower) and is_none_or_numeric(upper))
if uses_array and axis is None:
with pytest.raises(ValueError):
df.clip(lower=lower, upper=upper, axis=axis)
Comment on lines +540 to +541
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's possible (but not required) that you could also handle this via typing checks by creating overloads that are the acceptable combinations of the arguments lower, upper and axis

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's possible (but not required) that you could also handle this via typing checks by creating overloads that are the acceptable combinations of the arguments lower, upper and axis

I'm OK to approve this as is, but let me know if you want to try to make these changes I suggested as part of this PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure how to type the fact that "either one of lower or upper is ArrayLike". If you have any suggestion to propose, i can add overloads

Regarding the test i think it should stay as-is, as it tests the pandas version of the function

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just thinking of this implementation. One question though: the case where upper and lower are both arrays is covered by both overloads. Is that an issue ? I'm not that familiar with overloads in general

    @overload
    def clip(
        self,
        lower: AnyArrayLike = ...,
        upper: float | AnyArrayLike | None = ...,
        *,
        axis: Axis = ...,
        inplace: _bool = ...,
        **kwargs,
    ) -> DataFrame: ...
    @overload
    def clip(
        self,
        lower: float | AnyArrayLike | None = ...,
        upper: AnyArrayLike = ...,
        *,
        axis: Axis = ...,
        inplace: _bool = ...,
        **kwargs,
    ) -> DataFrame: ...

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure how to type the fact that "either one of lower or upper is ArrayLike". If you have any suggestion to propose, i can add overloads

I don't think that is required. df.clip() works fine, as does df.clip(3, 4). So maybe your test isn't right?

Regarding the test i think it should stay as-is, as it tests the pandas version of the function

If you can get the overloads to work, then you'd add tests using TYPE_CHECKING_INVALID_USAGE to make sure the type checkers caught the invalid usage. But I'm now not sure the overloads are needed.

Copy link
Contributor Author

@ldouteau ldouteau Aug 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe your test isn't right?

Well the test is not exhaustive: df.clip([1, 2]) will pass but df.clip(pd.Series([1, 2])) will fail with a value error.

What's your opinion on this ? Getting dedicated overloads using pd.Series ?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just thinking of this implementation. One question though: the case where upper and lower are both arrays is covered by both overloads. Is that an issue ?

I think the solution here is to disallow None as follows:

    @overload
    def clip(
        self,
        lower:  AnyArrayLike,
        upper: float | AnyArrayLike | None,
        axis: None,
        *,
        inplace: _bool = ...,
        **kwargs,
    ) -> Never: ...
    @overload
    def clip(
        self,
        lower:  float | AnyArrayLike | None,
        upper:  AnyArrayLike,
        axis: None,
        *,
        inplace: _bool = ...,
        **kwargs,
    ) -> Never: ...

Testing this means you have to move away from using pytest.mark.parameterize, and explicitly test each possible condition. This is preferred anyway from how we want to test the types.

You can use assert_never() to test the cases where it should fail.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe your test isn't right?

Well the test is not exhaustive: df.clip([1, 2]) will pass but df.clip(pd.Series([1, 2])) will fail with a value error.

What's your opinion on this ? Getting dedicated overloads using pd.Series ?

maybe your test isn't right?

Well the test is not exhaustive: df.clip([1, 2]) will pass but df.clip(pd.Series([1, 2])) will fail with a value error.

What's your opinion on this ? Getting dedicated overloads using pd.Series ?

I think this is pretty complicated, because you need to have overloads for each combination where axis=None and using AnyArrayLike corresponds to Never, but using AnyArrayLike requires axis to be specified and not be None.

I'm going to approve this PR as is - it's an improvement, and if you want to experiment with the overloads, that could be a separate PR. Created #984 to track that.

else:
assert_type(df.clip(lower=lower, upper=upper, axis=axis), pd.DataFrame)
ldouteau marked this conversation as resolved.
Show resolved Hide resolved


def test_types_abs() -> None:
Expand Down
Loading