Skip to content

Fix annotations for DataFrame.apply() including additional overloads #448

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 5 commits into from
Dec 5, 2022
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
8 changes: 7 additions & 1 deletion pandas-stubs/_typing.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ from typing import (
Iterator,
Literal,
Mapping,
MutableSequence,
Optional,
Protocol,
Sequence,
Expand Down Expand Up @@ -151,10 +152,15 @@ num: TypeAlias = complex
SeriesAxisType: TypeAlias = Literal[
"index", 0
] # Restricted subset of _AxisType for series
AxisType: TypeAlias = Literal["columns", "index", 0, 1]
AxisTypeIndex: TypeAlias = Literal["index", 0]
AxisTypeColumn: TypeAlias = Literal["columns", 1]
AxisType: TypeAlias = AxisTypeIndex | AxisTypeColumn
DtypeNp = TypeVar("DtypeNp", bound=np.dtype[np.generic])
KeysArgType: TypeAlias = Any
ListLike = TypeVar("ListLike", Sequence, np.ndarray, "Series", "Index")
ListLikeExceptSeriesAndStr = TypeVar(
"ListLikeExceptSeriesAndStr", MutableSequence, np.ndarray, tuple, "Index"
)
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 agree, the name is awful, but do we have a better way to exclude str from list-likes?

Copy link
Collaborator

Choose a reason for hiding this comment

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

I don't know of any

ListLikeU: TypeAlias = Union[Sequence, np.ndarray, Series, Index]
StrLike: TypeAlias = Union[str, np.str_]
Scalar: TypeAlias = Union[
Expand Down
103 changes: 97 additions & 6 deletions pandas-stubs/core/frame.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ from pandas._typing import (
Axes,
Axis,
AxisType,
AxisTypeColumn,
AxisTypeIndex,
CalculationMethod,
ColspaceArgType,
CompressionOptions,
Expand All @@ -82,6 +84,7 @@ from pandas._typing import (
Label,
Level,
ListLike,
ListLikeExceptSeriesAndStr,
ListLikeU,
MaskType,
MergeHow,
Expand Down Expand Up @@ -1086,36 +1089,124 @@ class DataFrame(NDFrame, OpsMixin):
*args,
**kwargs,
) -> DataFrame: ...

# First set of apply() overloads is with defaults
@overload
def apply(
self,
f: Callable[..., Series],
axis: AxisType = ...,
f: Callable[..., ListLikeExceptSeriesAndStr | Series],
axis: AxisTypeIndex = ...,
raw: _bool = ...,
result_type: Literal["expand", "reduce", "broadcast"] | None = ...,
result_type: Literal[None] = ...,
args=...,
**kwargs,
) -> DataFrame: ...
@overload
def apply(
self,
f: Callable[..., Scalar],
axis: AxisTypeIndex = ...,
raw: _bool = ...,
result_type: Literal[None] = ...,
args=...,
**kwargs,
) -> Series: ...

# Second set of apply() overloads is with keyword result_type
@overload
def apply(
self,
f: Callable[..., ListLikeExceptSeriesAndStr],
axis: AxisType = ...,
raw: _bool = ...,
result_type: Literal["expand", "reduce"] | None = ...,
args=...,
*,
result_type: Literal["reduce"],
**kwargs,
) -> Series: ...
@overload
def apply(
self,
f: Callable[..., Scalar],
result_type: Literal["broadcast"],
f: Callable[..., ListLikeExceptSeriesAndStr | Series],
axis: AxisType = ...,
raw: _bool = ...,
args=...,
*,
result_type: Literal["expand"],
**kwargs,
) -> DataFrame: ...
@overload
def apply(
self,
f: Callable[..., ListLikeExceptSeriesAndStr | Series],
axis: AxisType = ...,
raw: _bool = ...,
args=...,
*,
result_type: Literal["broadcast"],
**kwargs,
) -> DataFrame: ...

# Third set of apply() overloads is with keyword axis=1, but only where the return values have changed
@overload
def apply(
self,
f: Callable[..., ListLikeExceptSeriesAndStr | Scalar],
raw: _bool = ...,
result_type: Literal[None] = ...,
args=...,
*,
axis: AxisTypeColumn,
**kwargs,
) -> Series: ...
@overload
def apply(
self,
f: Callable[..., Series],
raw: _bool = ...,
result_type: Literal[None] = ...,
args=...,
*,
axis: AxisTypeColumn,
**kwargs,
) -> DataFrame: ...

# Fourth set of apply() overloads is with keyword axis=1 and keyword result_type
@overload
def apply(
self,
f: Callable[..., ListLikeExceptSeriesAndStr],
raw: _bool = ...,
args=...,
*,
axis: AxisTypeColumn = ...,
result_type: Literal["reduce"],
**kwargs,
) -> Series: ...
@overload
def apply(
self,
f: Callable[..., ListLikeExceptSeriesAndStr | Series],
raw: _bool = ...,
args=...,
*,
axis: AxisTypeColumn = ...,
result_type: Literal["expand"],
**kwargs,
) -> DataFrame: ...
@overload
def apply(
self,
f: Callable[..., ListLikeExceptSeriesAndStr | Series],
raw: _bool = ...,
args=...,
*,
axis: AxisTypeColumn = ...,
result_type: Literal["broadcast"],
**kwargs,
) -> DataFrame: ...

# Add spacing between apply() overloads and remaining annotations
def applymap(
self, func: Callable, na_action: Literal["ignore"] | None = ..., **kwargs
) -> DataFrame: ...
Expand Down
194 changes: 185 additions & 9 deletions tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,21 +462,21 @@ def test_types_unique() -> None:


def test_types_apply() -> None:
df = pd.DataFrame(data={"col1": [2, 1], "col2": [3, 4]})
df = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4], "col3": [5, 6]})

def returns_scalar(x: pd.Series) -> float:
return 2

def returns_series(x: pd.Series) -> pd.Series:
return x**2

check(assert_type(df.apply(returns_series), pd.DataFrame), pd.DataFrame)
def returns_listlike_of_2(x: pd.Series) -> tuple[int, int]:
return (7, 8)

def returns_scalar(x: pd.Series) -> float:
return 2
def returns_listlike_of_3(x: pd.Series) -> tuple[int, int, int]:
return (7, 8, 9)

check(assert_type(df.apply(returns_scalar), pd.Series), pd.Series)
check(
assert_type(df.apply(returns_scalar, result_type="broadcast"), pd.DataFrame),
pd.DataFrame,
)
# Misc checks
check(assert_type(df.apply(np.exp), pd.DataFrame), pd.DataFrame)
check(assert_type(df.apply(str), pd.Series), pd.Series)

Expand All @@ -486,6 +486,182 @@ def gethead(s: pd.Series, y: int) -> pd.Series:

check(assert_type(df.apply(gethead, args=(4,)), pd.DataFrame), pd.DataFrame)

# Check scalar/series/list-like for default (None), and result type of expand, reduce, broadcast
check(
assert_type(df.apply(returns_scalar), pd.Series),
pd.Series,
)
check(
assert_type(df.apply(returns_series), pd.DataFrame),
pd.DataFrame,
)
check(
assert_type(df.apply(returns_listlike_of_3), pd.DataFrame),
pd.DataFrame,
)

# While this call works in reality, it errors in the type checker, because this should never be called
# It does not make sense to pass a result_type of "expand" to a scalar return
# check(
# assert_type(
# df.apply(returns_scalar, result_type="expand"), pd.DataFrame
# ),
# pd.DataFrame,
# )
check(
assert_type(df.apply(returns_series, result_type="expand"), pd.DataFrame),
pd.DataFrame,
)
check(
assert_type(
df.apply(returns_listlike_of_3, result_type="expand"), pd.DataFrame
),
pd.DataFrame,
)

# While this call works in reality, it errors in the type checker, because this should never be called
# It does not make sense to pass a result_type of "reduce" to a scalar or series return
# check(
# assert_type(
# df.apply(returns_scalar, result_type="reduce"), pd.DataFrame
# ),
# pd.DataFrame,
# )
# check(
# assert_type(
# df.apply(returns_series, result_type="reduce"), pd.Series
# ),
# pd.Series,
# )
check(
assert_type(df.apply(returns_listlike_of_3, result_type="reduce"), pd.Series),
pd.Series,
)

# While this call works in reality, it errors in the type checker, because this should never be called
# It does not make sense to pass a result_type of "broadcast" to a scalar return
# check(
# assert_type(
# df.apply(returns_scalar, result_type="broadcast"), pd.DataFrame
# ),
# pd.DataFrame,
# )
check(
assert_type(df.apply(returns_series, result_type="broadcast"), pd.DataFrame),
pd.DataFrame,
)
check(
assert_type(
# Can only broadcast a list-like of 2 elements, not 3, because there are 2 rows
df.apply(returns_listlike_of_2, result_type="broadcast"),
pd.DataFrame,
),
pd.DataFrame,
)

# Check the same combinations with axis=1
check(
assert_type(df.apply(returns_scalar, axis=1), pd.Series),
pd.Series,
)
check(
assert_type(df.apply(returns_series, axis=1), pd.DataFrame),
pd.DataFrame,
)
check(
assert_type(df.apply(returns_listlike_of_3, axis=1), pd.Series),
pd.Series,
)

# While this call works in reality, it errors in the type checker, because this should never be called
# It does not make sense to pass a result_type of "expand" to a scalar return
# check(
# assert_type(
# df.apply(returns_scalar, axis=1, result_type="expand"), pd.DataFrame
# ),
# pd.DataFrame,
# )
check(
assert_type(
df.apply(returns_series, axis=1, result_type="expand"), pd.DataFrame
),
pd.DataFrame,
)
check(
assert_type(
df.apply(returns_listlike_of_3, axis=1, result_type="expand"), pd.DataFrame
),
pd.DataFrame,
)

# While this call works in reality, it errors in the type checker, because this should never be called
# It does not make sense to pass a result_type of "reduce" to a scalar or series return
# check(
# assert_type(
# df.apply(returns_scalar, axis=1, result_type="reduce"), pd.DataFrame
# ),
# pd.DataFrame,
# )
# check(
# assert_type(
# df.apply(returns_series, axis=1, result_type="reduce"), pd.DataFrame
# ),
# pd.DataFrame,
# )
check(
assert_type(
df.apply(returns_listlike_of_3, axis=1, result_type="reduce"), pd.Series
),
pd.Series,
)

# While this call works in reality, it errors in the type checker, because this should never be called
# It does not make sense to pass a result_type of "broadcast" to a scalar return
# check(
# assert_type(
# df.apply(returns_scalar, axis=1, result_type="broadcast"), pd.DataFrame
# ),
# pd.DataFrame,
# )
check(
assert_type(
df.apply(returns_series, axis=1, result_type="broadcast"), pd.DataFrame
),
pd.DataFrame,
)
check(
assert_type(
# Can only broadcast a list-like of 3 elements, not 2, as there are 3 columns
df.apply(returns_listlike_of_3, axis=1, result_type="broadcast"),
pd.DataFrame,
),
pd.DataFrame,
)

# Test various other argument combinations to ensure all overloads are supported
check(
assert_type(df.apply(returns_scalar, axis=0), pd.Series),
pd.Series,
)
check(
assert_type(df.apply(returns_scalar, axis=0, result_type=None), pd.Series),
pd.Series,
)
check(
assert_type(df.apply(returns_scalar, 0, False, None), pd.Series),
pd.Series,
)
check(
assert_type(df.apply(returns_scalar, 0, False, result_type=None), pd.Series),
pd.Series,
)
check(
assert_type(
df.apply(returns_scalar, 0, raw=False, result_type=None), pd.Series
),
pd.Series,
)


def test_types_applymap() -> None:
df = pd.DataFrame(data={"col1": [2, 1], "col2": [3, 4]})
Expand Down