Skip to content

GH456 First attempt GroupBy.transform improved typing #1242

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

Merged
merged 8 commits into from
Jun 13, 2025

Conversation

loicdiridollou
Copy link
Member

Copy link
Collaborator

@Dr-Irv Dr-Irv left a comment

Choose a reason for hiding this comment

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

Good idea. I think it won't close 456, because that was also about agg .

@loicdiridollou
Copy link
Member Author

For

I think you should just copy what is in the source pandas.core.groupby.base.py into pandas.core.groupby.base.pyi so they are equivalent, but change the frozenset to be Literal

is there a convention to name the TypeAlias or should we keep the same name as in the pandas code?

@Dr-Irv
Copy link
Collaborator

Dr-Irv commented Jun 7, 2025

For

I think you should just copy what is in the source pandas.core.groupby.base.py into pandas.core.groupby.base.pyi so they are equivalent, but change the frozenset to be Literal

is there a convention to name the TypeAlias or should we keep the same name as in the pandas code?

Probably shouldn't use the same name, because then the types won't match. Not that anyone should be importing that anyway. So keep the same name and append _type after the name.


@dataclasses.dataclass(order=True, frozen=True)
class OutputKey:
label: Hashable
position: int

reduction_kernels: TypeAlias = Literal[
Copy link
Collaborator

Choose a reason for hiding this comment

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

as commented elsewhere, lets call this reduction_kernels_type so that the types of the objects line up.

Comment on lines 1083 to 1084
# type of `sum` not well inferred by mypy
return sum(s)
Copy link
Collaborator

Choose a reason for hiding this comment

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

why not use s.sum() ?

Copy link
Member Author

Choose a reason for hiding this comment

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

The issue was if I passed sum the builtin one in the aggregate method directly, here is does not change anything.

return s.astype(float).min()

s = pd.Series([1, 2, 3, 4])
s.groupby([1, 1, 2, 2]).agg(lambda x: x.astype(float).min())
Copy link
Collaborator

Choose a reason for hiding this comment

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

don't you want a check(assert_type(... here?

Copy link
Member Author

Choose a reason for hiding this comment

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

Correct my mistake

Copy link
Member Author

Choose a reason for hiding this comment

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

Turns out the inference on the fly of lambdas is not super clear so you need to define the function on the side to have the right types.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Yes, that is an issue with lambda functions.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Actually, I think you can have a test of

check(assert_type(    s.groupby([1, 1, 2, 2]).agg(lambda x: x.astype(float).min()), pd.Series), pd.Series)

which would be worthwhile

Comment on lines 1157 to 1158
# type of `sum` not well inferred by mypy
return sum(s)
Copy link
Collaborator

Choose a reason for hiding this comment

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

use s.sum()

@loicdiridollou loicdiridollou requested a review from Dr-Irv June 7, 2025 15:11
check(
assert_type(s.groupby(level=0).agg([min, sum]), pd.DataFrame), pd.DataFrame
)


def test_types_groupby_transform() -> None:
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think you should add tests for two of the string transform arguments (e.g., "mean", "first")

Comment on lines 84 to 88
def aggregate(
self,
func: AggFuncTypeBase | None = ...,
/,
*args,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Before this overload, you could add this overload:

    @overload
    def aggregate(
        self,
        func: Callable[[Series], S2],
        *args,
        engine: WindowingEngine = ...,
        engine_kwargs: WindowingEngineKwargs = ...,
        **kwargs,
    ) -> Series[S2]: ...

Then you know that if you start with a Series with a known type, then the return type would be inferred from the callable. And it works with a lambda function, e.g.:

    s = pd.Series([1, 2, 3, 4])
    q = s.groupby([1, 1, 2, 2]).agg(lambda x: x.astype(float).min())

In this case, q would have type Series[float], which is what you want.

Copy link
Member Author

Choose a reason for hiding this comment

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

image Even with the new overload mypy still complains (pyright does not). I think it does not recognize the lamda as returning S2 (float).

Copy link
Collaborator

Choose a reason for hiding this comment

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

I think that's because the type of new_func isn't clear.

But I think it would work if you did check(assert_type(s.groupby([1,1,2,2]).agg(lambda x: x.astype(float).min()), "pd.Series[int]"), pd.Series, int)

Because then it can know that x is a Series[int] and that the lambda becomes Series[int]

Can you try that?

Copy link
Member Author

Choose a reason for hiding this comment

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

I tried that for the last push, see

check(assert_type(s.groupby([1,1,2,2]).agg(lambda x: x.astype(float).min()), "pd.Series[float]"), pd.Series, int)

It fails in all CI:

===========================================
Beginning: 'Run mypy on 'tests' (using the local stubs) and on the local stubs'
===========================================

tests/test_series.py:1167: error: Expression is of type "Series[Any]", not "Series[float]"  [assert-type]
Found 1 error in 1 file (checked 224 source files)

Copy link
Member Author

Choose a reason for hiding this comment

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

When I look with how mypy reads the type of the lambda, it has no idea about the type of x:

tests/test_series.py:1168: note: Revealed type is "def (x: Any) -> Any"

so that may explain why it fails on lambda expressions whatsoever.

Copy link
Collaborator

Choose a reason for hiding this comment

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

OK - so we can leave the lambda test in, but just have it assert_type() against Series instead of Series[float]

@@ -1147,6 +1165,9 @@ def func(s: pd.Series[int]) -> float:
np.floating,
)

# test below passes with mypy but pyright correctly sees it as pd.Series[float]
# check(assert_type(s.groupby([1,1,2,2]).agg(lambda x: x.astype(float).min()), pd.Series), pd.Series, float)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Keep the commented test in there so it is still there and executes, since it works for both type checkers, but comment out the one that is "better" that has pyright infer it as Series[float].

Copy link
Member Author

Choose a reason for hiding this comment

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

I am forced to comment it out because pyright sees it as pd.Series[float] but mypy sees it as pd.Series so in both versions the CI will fail either for mypy or pyright step. What would you recommend doing?

Copy link
Collaborator

Choose a reason for hiding this comment

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

I guess you have to keep it commented out. Do you have a test like this that passes both checkers:

func: Callable[[pd.Series], float] = lambda x: x.astype(float).min()
check(assert_type(s.groupby([1,1,2,2]).agg(func), "pd.Series[float]"), pd.Series, float)

So you can have the "preferred" version in there commented out, but I think the above test would pass both type checkers.

Copy link
Member Author

Choose a reason for hiding this comment

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

Actually that also fails to pass with mypy (pyright is fine with it).

Copy link
Collaborator

Choose a reason for hiding this comment

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

I tried a bunch of ideas and couldn't get it to work. It's probably a mypy bug, but I couldn't come up with a simple example that illustrates the problem.

Copy link
Collaborator

@Dr-Irv Dr-Irv left a comment

Choose a reason for hiding this comment

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

Just have to adjust that comment, then we are good to go.

np.floating,
)

# test below passes with mypy but pyright correctly sees it as pd.Series[float]
Copy link
Collaborator

Choose a reason for hiding this comment

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

Just have to change the comment to say "fails with mypy"

@loicdiridollou loicdiridollou requested a review from Dr-Irv June 13, 2025 22:21
Copy link
Collaborator

@Dr-Irv Dr-Irv left a comment

Choose a reason for hiding this comment

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

@Dr-Irv Dr-Irv merged commit b12c28d into pandas-dev:main Jun 13, 2025
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Create more precise annotations for DataFrame/Series GroupBy operations (agg, apply, transform)
2 participants