Skip to content

Commit 6339b66

Browse files
author
samuel.oranyeli
committed
create groupby accessor and method
1 parent 0bd644b commit 6339b66

File tree

1 file changed

+43
-4
lines changed

1 file changed

+43
-4
lines changed

pandas_flavor/register.py

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Register functions as methods of Pandas DataFrame and Series."""
2+
23
from __future__ import annotations
34

45
import warnings
@@ -323,7 +324,7 @@ def register_groupby_accessor(name: str):
323324
return _register_accessor(name, DataFrameGroupBy)
324325

325326

326-
def register_groupby_method(method: Callable) -> Callable:
327+
def register_groupby_method(method: Callable):
327328
"""Register a function as a method attached to the pandas DataFrameGroupBy.
328329
329330
Example:
@@ -335,22 +336,60 @@ def register_groupby_method(method: Callable) -> Callable:
335336
!!! info "New in version 0.7.0"
336337
337338
Args:
338-
method: Function to be registered as a method on the DataFrame.
339+
method: Function to be registered as a method
340+
on the DataFrameGroupBy object.
339341
340342
Returns:
341-
A Callable.
343+
callable: The original method.
342344
"""
345+
method_signature = inspect.signature(method)
343346

344347
def inner(*args: tuple, **kwargs: dict):
348+
"""Inner function to register the method.
349+
350+
This function is called when the user
351+
decorates a function with register_groupby_method.
352+
353+
Args:
354+
*args: The arguments to pass to the registered method.
355+
**kwargs: The keyword arguments to pass to the registered method.
356+
357+
Returns:
358+
method: The original method.
359+
"""
360+
345361
class AccessorMethod(object):
362+
"""DataFrameGroupBy Accessor method class."""
363+
346364
__doc__ = method.__doc__
347365

348366
def __init__(self, obj):
367+
"""Initialize the accessor method class.
368+
369+
Args:
370+
obj: The pandas DataFrameGroupBy object.
371+
"""
349372
self._obj = obj
350373

351374
@wraps(method)
352375
def __call__(self, *args, **kwargs):
353-
return method(self._obj, *args, **kwargs)
376+
"""Call the accessor method.
377+
378+
Args:
379+
*args: The arguments to pass to the registered method.
380+
**kwargs: The keyword arguments to pass
381+
to the registered method.
382+
383+
Returns:
384+
object: The result of calling of the method.
385+
"""
386+
global method_call_ctx_factory
387+
if method_call_ctx_factory is None:
388+
return method(self._obj, *args, **kwargs)
389+
390+
return handle_pandas_extension_call(
391+
method, method_signature, self._obj, args, kwargs
392+
)
354393

355394
register_groupby_accessor(method.__name__)(AccessorMethod)
356395
return method

0 commit comments

Comments
 (0)