|
1 | 1 | """Register functions as methods of Pandas DataFrame and Series."""
|
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import warnings |
2 | 6 | from functools import wraps
|
| 7 | + |
| 8 | +from pandas.core.groupby.generic import DataFrameGroupBy |
| 9 | +from pandas.util._exceptions import find_stack_level |
3 | 10 | from pandas.api.extensions import (
|
4 | 11 | register_series_accessor,
|
5 | 12 | register_dataframe_accessor,
|
@@ -228,3 +235,162 @@ def __call__(self, *args, **kwargs):
|
228 | 235 | return method
|
229 | 236 |
|
230 | 237 | return inner()
|
| 238 | + |
| 239 | + |
| 240 | +# variant of pandas' accessor |
| 241 | + |
| 242 | +# copied from pandas' accessor file - pandas/pandas/core/accessor.py |
| 243 | +""" |
| 244 | +
|
| 245 | +accessor.py contains base classes for implementing accessor properties |
| 246 | +that can be mixed into or pinned onto other pandas classes. |
| 247 | +
|
| 248 | +""" |
| 249 | + |
| 250 | + |
| 251 | +class CachedAccessor: |
| 252 | + """ |
| 253 | + Custom property-like object. |
| 254 | +
|
| 255 | + A descriptor for caching accessors. |
| 256 | +
|
| 257 | + Parameters |
| 258 | + ---------- |
| 259 | + name : str |
| 260 | + Namespace that will be accessed under, e.g. ``df.foo``. |
| 261 | + accessor : DataFrameGroupBy |
| 262 | + Class with the extension methods. |
| 263 | +
|
| 264 | + Notes |
| 265 | + ----- |
| 266 | + For accessor, The class's __init__ method assumes that one of |
| 267 | + ``Series``, ``DataFrame`` or ``Index`` as the |
| 268 | + single argument ``data``. |
| 269 | + """ |
| 270 | + |
| 271 | + def __init__(self, name: str, accessor: DataFrameGroupBy) -> None: |
| 272 | + self._name = name |
| 273 | + self._accessor = accessor |
| 274 | + |
| 275 | + def __get__(self, obj, cls): |
| 276 | + if obj is None: |
| 277 | + # we're accessing the attribute of the class, i.e., Dataset.geo |
| 278 | + return self._accessor |
| 279 | + accessor_obj = self._accessor(obj) |
| 280 | + # Replace the property with the accessor object. Inspired by: |
| 281 | + # https://www.pydanny.com/cached-property.html |
| 282 | + # We need to use object.__setattr__ because we overwrite __setattr__ on |
| 283 | + # NDFrame |
| 284 | + object.__setattr__(obj, self._name, accessor_obj) |
| 285 | + return accessor_obj |
| 286 | + |
| 287 | + |
| 288 | +def _register_accessor(name: str, cls: DataFrameGroupBy): |
| 289 | + """ |
| 290 | + Register a custom accessor on a DataFrameGroupBy object. |
| 291 | +
|
| 292 | + Args: |
| 293 | + name : str |
| 294 | + Name under which the accessor should be registered. |
| 295 | + A warning is issued |
| 296 | + if this name conflicts with a preexisting attribute. |
| 297 | + cls: DataFrameGroupBy |
| 298 | +
|
| 299 | + Returns: |
| 300 | + A class decorator. |
| 301 | + """ |
| 302 | + |
| 303 | + def decorator(accessor): |
| 304 | + if hasattr(cls, name): |
| 305 | + warnings.warn( |
| 306 | + f"registration of accessor {repr(accessor)} under name " |
| 307 | + f"{repr(name)} for type {repr(cls)} " |
| 308 | + "is overriding a preexisting " |
| 309 | + f"attribute with the same name.", |
| 310 | + UserWarning, |
| 311 | + stacklevel=find_stack_level(), |
| 312 | + ) |
| 313 | + setattr(cls, name, CachedAccessor(name, accessor)) |
| 314 | + if not hasattr(cls, "_accessors"): |
| 315 | + cls._accessors = set() |
| 316 | + cls._accessors.add(name) |
| 317 | + return accessor |
| 318 | + |
| 319 | + return decorator |
| 320 | + |
| 321 | + |
| 322 | +def register_groupby_accessor(name: str): |
| 323 | + return _register_accessor(name, DataFrameGroupBy) |
| 324 | + |
| 325 | + |
| 326 | +def register_groupby_method(method): |
| 327 | + """Register a function as a method attached to the pandas DataFrameGroupBy. |
| 328 | +
|
| 329 | + Example: |
| 330 | + >>> @register_groupby_method # doctest: +SKIP |
| 331 | + >>> def print_column(grp, col): # doctest: +SKIP |
| 332 | + ... '''Print the dataframe column given''' # doctest: +SKIP |
| 333 | + ... print(grp[col]) # doctest: +SKIP |
| 334 | +
|
| 335 | + !!! info "New in version 0.7.0" |
| 336 | +
|
| 337 | + Args: |
| 338 | + method: Function to be registered as a method |
| 339 | + on the DataFrameGroupBy object. |
| 340 | +
|
| 341 | + Returns: |
| 342 | + callable: The original method. |
| 343 | + """ |
| 344 | + method_signature = inspect.signature(method) |
| 345 | + |
| 346 | + def inner(*args: tuple, **kwargs: dict): |
| 347 | + """Inner function to register the method. |
| 348 | +
|
| 349 | + This function is called when the user |
| 350 | + decorates a function with register_groupby_method. |
| 351 | +
|
| 352 | + Args: |
| 353 | + *args: The arguments to pass to the registered method. |
| 354 | + **kwargs: The keyword arguments to pass to the registered method. |
| 355 | +
|
| 356 | + Returns: |
| 357 | + method: The original method. |
| 358 | + """ |
| 359 | + |
| 360 | + class AccessorMethod(object): |
| 361 | + """DataFrameGroupBy Accessor method class.""" |
| 362 | + |
| 363 | + __doc__ = method.__doc__ |
| 364 | + |
| 365 | + def __init__(self, obj): |
| 366 | + """Initialize the accessor method class. |
| 367 | +
|
| 368 | + Args: |
| 369 | + obj: The pandas DataFrameGroupBy object. |
| 370 | + """ |
| 371 | + self._obj = obj |
| 372 | + |
| 373 | + @wraps(method) |
| 374 | + def __call__(self, *args, **kwargs): |
| 375 | + """Call the accessor method. |
| 376 | +
|
| 377 | + Args: |
| 378 | + *args: The arguments to pass to the registered method. |
| 379 | + **kwargs: The keyword arguments to pass |
| 380 | + to the registered method. |
| 381 | +
|
| 382 | + Returns: |
| 383 | + object: The result of calling of the method. |
| 384 | + """ |
| 385 | + global method_call_ctx_factory |
| 386 | + if method_call_ctx_factory is None: |
| 387 | + return method(self._obj, *args, **kwargs) |
| 388 | + |
| 389 | + return handle_pandas_extension_call( |
| 390 | + method, method_signature, self._obj, args, kwargs |
| 391 | + ) |
| 392 | + |
| 393 | + register_groupby_accessor(method.__name__)(AccessorMethod) |
| 394 | + return method |
| 395 | + |
| 396 | + return inner() |
0 commit comments