Skip to content

Fix groupby.apply() and sum(axis=1) #168

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 3 commits into from
Jul 25, 2022
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
10 changes: 5 additions & 5 deletions pandas-stubs/core/frame.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -1906,22 +1906,22 @@ class DataFrame(NDFrame, OpsMixin):
self,
axis: AxisType | None = ...,
skipna: _bool | None = ...,
level: None = ...,
numeric_only: _bool | None = ...,
min_count: int = ...,
*,
level: Level,
**kwargs,
) -> DataFrame: ...
) -> Series: ...
@overload
def sum(
self,
axis: AxisType | None = ...,
skipna: _bool | None = ...,
level: None = ...,
numeric_only: _bool | None = ...,
min_count: int = ...,
*,
level: Level,
**kwargs,
) -> Series: ...
) -> DataFrame: ...
def swapaxes(
self, axis1: AxisType, axis2: AxisType, copy: _bool = ...
) -> DataFrame: ...
Expand Down
13 changes: 12 additions & 1 deletion pandas-stubs/core/groupby/generic.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ from __future__ import annotations
from typing import (
Any,
Callable,
Iterable,
Iterator,
Literal,
NamedTuple,
Expand Down Expand Up @@ -111,7 +112,17 @@ class _DataFrameGroupByNonScalar(DataFrameGroupBy):
class DataFrameGroupBy(GroupBy):
def any(self, skipna: bool = ...) -> DataFrame: ...
def all(self, skipna: bool = ...) -> DataFrame: ...
def apply(self, func, *args, **kwargs) -> DataFrame: ...
# mypy sees the two overloads as overlapping
@overload
def apply( # type: ignore[misc]
self, func: Callable[[DataFrame], Series | Scalar], *args, **kwargs
) -> Series: ...
@overload
def apply( # type: ignore[misc]
Copy link
Member

Choose a reason for hiding this comment

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

I replaced my local version of generic.pyi with this one and it seems that neither pyright nor mypy need these two ignores (I would have thought both of them need ignores, a DataFrame is Iterable).

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

If I remove both of these ignores, I get errors from both pyright and mypy

Copy link
Member

Choose a reason for hiding this comment

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

you are right, not sure what I messed up. Unless you add a test covering this second overload, I would be tempted to remove it.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

you are right, not sure what I messed up. Unless you add a test covering this second overload, I would be tempted to remove it.

There is a test already. That's why I needed to add the second overload.

df7: pd.DataFrame = df.groupby(by="col1").apply(sum)

Copy link
Member

Choose a reason for hiding this comment

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

Okay, I'm not a fan of this overload but it seems to work :)

self, func: Callable[[Iterable], Series | Scalar], *args, **kwargs
) -> DataFrame: ...
@overload
def apply(self, func: Callable, *args, **kwargs) -> DataFrame | Series: ...
@overload
def aggregate(self, arg: str, *args, **kwargs) -> DataFrame: ...
@overload
Expand Down
1 change: 0 additions & 1 deletion pandas-stubs/core/groupby/groupby.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ class BaseGroupBy(PandasObject, SelectionMixin[NDFrameT], GroupByIndexingMixin):
def pipe(self, func: Callable, *args, **kwargs): ...
plot = ...
def get_group(self, name, obj: DataFrame | None = ...) -> DataFrame: ...
def apply(self, func: Callable, *args, **kwargs) -> FrameOrSeriesUnion: ...

class GroupBy(BaseGroupBy[NDFrameT]):
def count(self) -> FrameOrSeriesUnion: ...
Expand Down
17 changes: 17 additions & 0 deletions tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from typing import (
TYPE_CHECKING,
Any,
Callable,
Hashable,
Iterable,
Iterator,
Expand Down Expand Up @@ -1339,3 +1340,19 @@ def test_setitem_list():
iter2: Iterator[tuple[str, int]] = (v for v in lst4)
check(assert_type(df.set_index(iter1), pd.DataFrame), pd.DataFrame)
check(assert_type(df.set_index(iter2), pd.DataFrame), pd.DataFrame)


def test_groupby_apply() -> None:
# GH 167
df = pd.DataFrame({"col1": [1, 2, 3], "col2": [4, 5, 6]})

def summean(x: pd.DataFrame) -> float:
return x.sum().mean()

check(assert_type(df.groupby("col1").apply(summean), pd.Series), pd.Series)

lfunc: Callable[[pd.DataFrame], float] = lambda x: x.sum().mean()
check(
assert_type(df.groupby("col1").apply(lfunc), pd.Series),
pd.Series,
)