Skip to content

add proper type when grouping by a Series #708

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 6 commits into from
Jun 2, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
22 changes: 20 additions & 2 deletions pandas-stubs/_typing.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -427,12 +427,30 @@ ByT = TypeVar(
Interval[Timedelta],
tuple,
)
# Use a distinct SeriesByT when using groupby with Series of known dtype.
# Essentially, an intersection between Series S1 TypeVar, and ByT TypeVar
SeriesByT = TypeVar(
"SeriesByT",
str,
Copy link
Collaborator

Choose a reason for hiding this comment

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

We've been recently advised to no longer use constrained TypeVars, so can you change this to SeriesByT = TypeVar("SeriesByT", bound=str | bytes | ...) We made the change for S1 in a recent 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.

Hi,

What is the difference between TypeVar("SeriesByT", bound = str | bytes ...) and TypeVar("SeriesByT, str, byts, ...) ?

I tried to replace the SeriesByT with the bound keyword, but then the mypy did not pass anymore :

Poe => mypy

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

pandas-stubs/core/series.pyi:648: error: Type variable "SeriesByT" not valid as type argument value for "SeriesGroupBy"  [type-var]
pandas-stubs/core/frame.pyi:1100: error: Type variable "SeriesByT" not valid as type argument value for "DataFrameGroupBy"  [type-var]
Found 2 errors in 2 files (checked 224 source files)

===========================================
Step: 'Run mypy on 'tests' (using the local stubs) and on the local stubs' failed!
===========================================

Copy link
Member

Choose a reason for hiding this comment

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

bound allows the type to be a union of all the listed types. Without it, the type has to be one of the listed (sub-)types.

You probably also need to adjust the type used for SeriesGroupBy and DataFrameGroupBy to use bound.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks I actually tried that and got rid of the errors.

bytes,
datetime.date,
bool,
int,
float,
complex,
Timestamp,
Timedelta,
Period,
Interval[int],
Interval[float],
Interval[Timestamp],
Interval[Timedelta],
)
GroupByObjectNonScalar: TypeAlias = (
tuple
| list[_HashableTa]
| Function
| list[Function]
| Series
| list[Series]
| np.ndarray
| list[np.ndarray]
Expand All @@ -442,7 +460,7 @@ GroupByObjectNonScalar: TypeAlias = (
| Grouper
| list[Grouper]
)
GroupByObject: TypeAlias = Scalar | Index | GroupByObjectNonScalar
GroupByObject: TypeAlias = Scalar | Index | GroupByObjectNonScalar | Series

StataDateFormat: TypeAlias = Literal[
"tc",
Expand Down
16 changes: 15 additions & 1 deletion pandas-stubs/core/frame.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ from pandas._typing import (
ReplaceMethod,
Scalar,
ScalarT,
SeriesByT,
SortKind,
StataDateFormat,
StorageOptions,
Expand Down Expand Up @@ -1085,7 +1086,20 @@ class DataFrame(NDFrame, OpsMixin):
@overload
def groupby(
self,
by: CategoricalIndex | Index,
by: Series[SeriesByT],
axis: Axis = ...,
level: Level | None = ...,
as_index: _bool = ...,
sort: _bool = ...,
group_keys: _bool = ...,
squeeze: _bool = ...,
observed: _bool = ...,
dropna: _bool = ...,
) -> DataFrameGroupBy[SeriesByT]: ...
@overload
def groupby(
self,
by: CategoricalIndex | Index | Series,
axis: Axis = ...,
level: Level | None = ...,
as_index: _bool = ...,
Expand Down
16 changes: 15 additions & 1 deletion pandas-stubs/core/series.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ from pandas._typing import (
Renamer,
ReplaceMethod,
Scalar,
SeriesByT,
SortKind,
StrDtypeArg,
TimedeltaDtypeArg,
Expand Down Expand Up @@ -639,7 +640,20 @@ class Series(IndexOpsMixin, NDFrame, Generic[S1]):
@overload
def groupby(
self,
by: CategoricalIndex | Index,
by: Series[SeriesByT],
axis: AxisIndex = ...,
level: Level | None = ...,
as_index: _bool = ...,
sort: _bool = ...,
group_keys: _bool = ...,
squeeze: _bool = ...,
observed: _bool = ...,
dropna: _bool = ...,
) -> SeriesGroupBy[S1, SeriesByT]: ...
@overload
def groupby(
self,
by: CategoricalIndex | Index | Series,
axis: AxisIndex = ...,
level: Level | None = ...,
as_index: _bool = ...,
Expand Down
14 changes: 14 additions & 0 deletions tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -985,6 +985,20 @@ def test_types_groupby_any() -> None:
)


def test_types_groupby_iter() -> None:
df = pd.DataFrame(data={"col1": [1, 1, 2], "col2": [3, 4, 5]})
series_groupby = pd.Series([True, True, False], dtype=bool)
first_group = next(iter(df.groupby(series_groupby)))
check(
assert_type(first_group[0], bool),
bool,
)
check(
assert_type(first_group[1], pd.DataFrame),
pd.DataFrame,
)


def test_types_merge() -> None:
df = pd.DataFrame(data={"col1": [1, 1, 2], "col2": [3, 4, 5]})
df2 = pd.DataFrame(data={"col1": [1, 1, 2], "col2": [0, 1, 0]})
Expand Down
11 changes: 11 additions & 0 deletions tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,17 @@ def test_types_group_by_with_dropna_keyword() -> None:
s.groupby(level=0).sum()


def test_types_groupby_iter() -> None:
s = pd.Series([1, 1, 2], dtype=int)
series_groupby = pd.Series([True, True, False], dtype=bool)
first_group = next(iter(s.groupby(series_groupby)))
check(
assert_type(first_group[0], bool),
bool,
)
check(assert_type(first_group[1], "pd.Series[int]"), pd.Series, np.integer)


def test_types_plot() -> None:
s = pd.Series([0, 1, 1, 0, -10])
if TYPE_CHECKING: # skip pytest
Expand Down