Skip to content

ENH: add dict to return type of func argument of DataFrame#apply #470

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 7 commits into from
Dec 19, 2022
2 changes: 1 addition & 1 deletion pandas-stubs/core/frame.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -1126,7 +1126,7 @@ class DataFrame(NDFrame, OpsMixin):
@overload
def apply(
self,
f: Callable[..., ListLikeExceptSeriesAndStr | Series],
f: Callable[..., ListLikeExceptSeriesAndStr | Series | dict],
axis: AxisType = ...,
raw: _bool = ...,
args=...,
Expand Down
11 changes: 11 additions & 0 deletions tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,9 @@ def returns_listlike_of_2(x: pd.Series) -> tuple[int, int]:
def returns_listlike_of_3(x: pd.Series) -> tuple[int, int, int]:
return (7, 8, 9)

def returns_dict(x: pd.Series) -> dict[str, int]:
return {"col4": 7, "col5": 8}

# Misc checks
check(assert_type(df.apply(np.exp), pd.DataFrame), pd.DataFrame)
check(assert_type(df.apply(str), "pd.Series[str]"), pd.Series, str)
Expand Down Expand Up @@ -518,6 +521,10 @@ def gethead(s: pd.Series, y: int) -> pd.Series:
),
pd.DataFrame,
)
check(
assert_type(df.apply(returns_dict, result_type="expand"), pd.DataFrame),
pd.DataFrame,
)

# Check various return types for result_type="reduce" with default axis (0)
check(
Expand Down Expand Up @@ -599,6 +606,10 @@ def gethead(s: pd.Series, y: int) -> pd.Series:
),
pd.DataFrame,
)
check(
assert_type(df.apply(returns_dict, axis=1, result_type="expand"), pd.DataFrame),
pd.DataFrame,
)

# Check various return types for result_type="reduce" with axis=1
check(
Expand Down