-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
API: Clarify difference between agg and apply for Series / DataFrame #49672
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
Closed
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -14,6 +14,7 @@ | |
Iterable, | ||
Iterator, | ||
List, | ||
Literal, | ||
Sequence, | ||
cast, | ||
) | ||
|
@@ -158,19 +159,54 @@ def agg(self) -> DataFrame | Series | None: | |
return self.apply_str() | ||
|
||
if is_dict_like(arg): | ||
return self.agg_dict_like() | ||
return self.dict_like("agg") | ||
elif is_list_like(arg): | ||
# we require a list, but not a 'str' | ||
return self.agg_list_like() | ||
return self.list_like("agg") | ||
|
||
if callable(arg): | ||
f = com.get_cython_func(arg) | ||
if f and not args and not kwargs: | ||
return getattr(obj, f)() | ||
elif not isinstance(obj, SelectionMixin): | ||
# i.e. obj is Series or DataFrame | ||
return self.agg_udf() | ||
|
||
# caller can react | ||
return None | ||
|
||
def agg_udf(self): | ||
obj = self.obj | ||
arg = cast(Callable, self.f) | ||
|
||
if not isinstance(obj, SelectionMixin): | ||
# i.e. obj is Series or DataFrame | ||
selected_obj = obj | ||
elif obj._selected_obj.ndim == 1: | ||
# For SeriesGroupBy this matches _obj_with_exclusions | ||
selected_obj = obj._selected_obj | ||
else: | ||
selected_obj = obj._obj_with_exclusions | ||
|
||
results = [] | ||
|
||
if selected_obj.ndim == 1: | ||
colg = obj._gotitem(selected_obj.name, ndim=1, subset=selected_obj) | ||
return arg(colg) | ||
|
||
indices = [] | ||
for index, col in enumerate(selected_obj): | ||
colg = obj._gotitem(col, ndim=1, subset=selected_obj.iloc[:, index]) | ||
new_res = arg(colg) | ||
results.append(new_res) | ||
indices.append(index) | ||
keys = selected_obj.columns.take(indices) | ||
|
||
from pandas import Series | ||
|
||
result = Series(results, index=keys) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. should we be using something._constructor here? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We could be using |
||
return result | ||
|
||
def transform(self) -> DataFrame | Series: | ||
""" | ||
Transform a DataFrame or Series. | ||
|
@@ -284,7 +320,7 @@ def transform_str_or_callable(self, func) -> DataFrame | Series: | |
except Exception: | ||
return func(obj, *args, **kwargs) | ||
|
||
def agg_list_like(self) -> DataFrame | Series: | ||
def list_like(self, method: Literal["agg", "apply"]) -> DataFrame | Series: | ||
""" | ||
Compute aggregation in the case of a list-like argument. | ||
|
||
|
@@ -316,7 +352,7 @@ def agg_list_like(self) -> DataFrame | Series: | |
if selected_obj.ndim == 1: | ||
for a in arg: | ||
colg = obj._gotitem(selected_obj.name, ndim=1, subset=selected_obj) | ||
new_res = colg.aggregate(a) | ||
new_res = getattr(colg, method)(a) | ||
results.append(new_res) | ||
|
||
# make sure we find a good name | ||
|
@@ -328,7 +364,7 @@ def agg_list_like(self) -> DataFrame | Series: | |
indices = [] | ||
for index, col in enumerate(selected_obj): | ||
colg = obj._gotitem(col, ndim=1, subset=selected_obj.iloc[:, index]) | ||
new_res = colg.aggregate(arg) | ||
new_res = getattr(colg, method)(arg) | ||
results.append(new_res) | ||
indices.append(index) | ||
keys = selected_obj.columns.take(indices) | ||
|
@@ -357,7 +393,7 @@ def agg_list_like(self) -> DataFrame | Series: | |
) | ||
return concatenated.reindex(full_ordered_index, copy=False) | ||
|
||
def agg_dict_like(self) -> DataFrame | Series: | ||
def dict_like(self, method: Literal["agg", "apply"]) -> DataFrame | Series: | ||
""" | ||
Compute aggregation in the case of a dict-like argument. | ||
|
||
|
@@ -382,16 +418,17 @@ def agg_dict_like(self) -> DataFrame | Series: | |
selected_obj = obj._selected_obj | ||
selection = obj._selection | ||
|
||
arg = self.normalize_dictlike_arg("agg", selected_obj, arg) | ||
arg = self.normalize_dictlike_arg(method, selected_obj, arg) | ||
|
||
if selected_obj.ndim == 1: | ||
# key only used for output | ||
colg = obj._gotitem(selection, ndim=1) | ||
results = {key: colg.agg(how) for key, how in arg.items()} | ||
results = {key: getattr(colg, method)(how) for key, how in arg.items()} | ||
else: | ||
# key used for column selection and output | ||
results = { | ||
key: obj._gotitem(key, ndim=1).agg(how) for key, how in arg.items() | ||
key: getattr(obj._gotitem(key, ndim=1), method)(how) | ||
for key, how in arg.items() | ||
} | ||
|
||
# set the final keys | ||
|
@@ -412,7 +449,7 @@ def agg_dict_like(self) -> DataFrame | Series: | |
ktu._set_names(selected_obj.columns.names) | ||
keys_to_use = ktu | ||
|
||
axis: AxisInt = 0 if isinstance(obj, ABCSeries) else 1 | ||
axis: AxisInt = 0 if isinstance(obj, ABCSeries) and method == "agg" else 1 | ||
result = concat( | ||
{k: results[k] for k in keys_to_use}, # type: ignore[misc] | ||
axis=axis, | ||
|
@@ -477,7 +514,10 @@ def apply_multiple(self) -> DataFrame | Series: | |
result: Series, DataFrame, or None | ||
Result when self.f is a list-like or dict-like, None otherwise. | ||
""" | ||
return self.obj.aggregate(self.f, self.axis, *self.args, **self.kwargs) | ||
if is_dict_like(self.f): | ||
return self.dict_like("apply") | ||
else: | ||
return self.list_like("apply") | ||
|
||
def normalize_dictlike_arg( | ||
self, how: str, obj: DataFrame | Series, func: AggFuncTypeDict | ||
|
@@ -676,9 +716,6 @@ def agg(self): | |
if axis == 1: | ||
result = result.T if result is not None else result | ||
|
||
if result is None: | ||
result = self.obj.apply(self.orig_f, axis, args=self.args, **self.kwargs) | ||
|
||
return result | ||
|
||
def apply_empty_result(self): | ||
|
@@ -1009,34 +1046,6 @@ def apply(self) -> DataFrame | Series: | |
# self.f is Callable | ||
return self.apply_standard() | ||
|
||
def agg(self): | ||
result = super().agg() | ||
if result is None: | ||
f = self.f | ||
kwargs = self.kwargs | ||
|
||
# string, list-like, and dict-like are entirely handled in super | ||
assert callable(f) | ||
|
||
# we can be called from an inner function which | ||
# passes this meta-data | ||
kwargs.pop("_level", None) | ||
|
||
# try a regular apply, this evaluates lambdas | ||
# row-by-row; however if the lambda is expected a Series | ||
# expression, e.g.: lambda x: x-x.quantile(0.25) | ||
# this will fail, so we can try a vectorized evaluation | ||
|
||
# we cannot FIRST try the vectorized evaluation, because | ||
# then .agg and .apply would have different semantics if the | ||
# operation is actually defined on the Series, e.g. str | ||
try: | ||
result = self.obj.apply(f) | ||
except (ValueError, AttributeError, TypeError): | ||
result = f(self.obj) | ||
|
||
return result | ||
|
||
def apply_empty_result(self) -> Series: | ||
obj = self.obj | ||
return obj._constructor(dtype=obj.dtype, index=obj.index).__finalize__( | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is "udf" here a shorthand for? Can you rename to something more explicit and/or add a doc string & type hints to help better understand this?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
User Defined Function; I'd prefer sticking with the name but completely agree it should be expanding upon in a docstring.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍