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 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
62 changes: 40 additions & 22 deletions pandas-stubs/_typing.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -407,33 +407,51 @@ Function: TypeAlias = np.ufunc | Callable[..., Any]
_HashableTa = TypeVar("_HashableTa", bound=Hashable)
ByT = TypeVar(
"ByT",
str,
bytes,
datetime.date,
datetime.datetime,
datetime.timedelta,
np.datetime64,
np.timedelta64,
bool,
int,
float,
complex,
Timestamp,
Timedelta,
Scalar,
Period,
Interval[int],
Interval[float],
Interval[Timestamp],
Interval[Timedelta],
tuple,
bound=str
| bytes
| datetime.date
| datetime.datetime
| datetime.timedelta
| np.datetime64
| np.timedelta64
| bool
| int
| float
| complex
| Timestamp
| Timedelta
| Scalar
| Period
| Interval[int]
| Interval[float]
| Interval[Timestamp]
| 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",
bound=str
| 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 @@ -443,7 +461,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 @@ -107,6 +107,7 @@ from pandas._typing import (
ReplaceMethod,
Scalar,
ScalarT,
SeriesByT,
SortKind,
StataDateFormat,
StorageOptions,
Expand Down Expand Up @@ -1087,7 +1088,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 @@ -130,6 +130,7 @@ from pandas._typing import (
Renamer,
ReplaceMethod,
Scalar,
SeriesByT,
SortKind,
StrDtypeArg,
TimedeltaDtypeArg,
Expand Down Expand Up @@ -635,7 +636,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 @@ -732,6 +732,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