<p>@Ch3steR,谢谢你帮我看到光明。不过我想详细说明一下你的答案</p>
<p>{a1}包括这些相关行</p>
<pre><code>def aggregate(
obj: AggObjType,
arg: AggFuncType,
*args,
**kwargs,
):
...
if isinstance(arg, str):
return obj._try_aggregate_string_function(arg, *args, **kwargs), None
</code></pre>
<p>然后我们追踪<a href="https://github.com/pandas-dev/pandas/blob/df32e83f36bf485be803be2b87d23135be30540a/pandas/core/base.py#L301" rel="nofollow noreferrer">^{<cd2>}</a></p>
<pre><code>def _try_aggregate_string_function(self, arg: str, *args, **kwargs):
"""
if arg is a string, then try to operate on it:
- try to find a function (or attribute) on ourselves
- try to find a numpy function
- raise
"""
assert isinstance(arg, str)
f = getattr(self, arg, None)
if f is not None:
if callable(f):
return f(*args, **kwargs)
# people may try to aggregate on a non-callable attribute
# but don't let them think they can pass args to it
assert len(args) == 0
assert len([kwarg for kwarg in kwargs if kwarg not in ["axis"]]) == 0
return f
f = getattr(np, arg, None)
if f is not None:
if hasattr(self, "__array__"):
# in particular exclude Window
return f(self, *args, **kwargs)
raise AttributeError(
f"'{arg}' is not a valid function for '{type(self).__name__}' object"
)
</code></pre>
<p>因此,当您进行类似<code>df.agg('foo')</code>的调用时,<strong>熊猫首先查找名为<code>foo</code>的数据帧属性,然后查找名为<code>foo</code></strong>的NumPy函数(假设<code>foo</code>不作为数据帧属性存在)</p>