小编Ami*_*azi的帖子

Python (pandas):使用使用 pandas API 的装饰器

我对 Python 上的一般装饰器和类很陌生,但有一个问题,是否有更好的方法来装饰 Pandas 对象。举个例子,我写了以下内容来创建两个方法——lisa 和 wil:

import numpy as np
import pandas as pd

test = np.array([['john', 'meg', 2.23, 6.49],
       ['lisa', 'wil', 9.67, 8.87],
       ['lisa', 'fay', 3.41, 5.04],
       ['lisa', 'wil', 0.58, 6.12],
       ['john', 'wil', 7.31, 1.74]],
)
test = pd.DataFrame(test)
test.columns = ['name1','name2','scoreA','scoreB']

@pd.api.extensions.register_dataframe_accessor('abc')
class ABCDataFrame:

    def __init__(self, pandas_obj):
        self._obj = pandas_obj

    @property
    def lisa(self):
        return self._obj.loc[self._obj['name1'] == 'lisa']
    @property
    def wil(self):
        return self._obj.loc[self._obj['name2'] == 'wil']
Run Code Online (Sandbox Code Playgroud)

示例输出如下:

test.abc.lisa.abc.wil
  name1 name2 scoreA scoreB
1  lisa   wil   9.67   8.87
3  lisa …
Run Code Online (Sandbox Code Playgroud)

python pandas python-decorators python-class

3
推荐指数
1
解决办法
387
查看次数

标签 统计

pandas ×1

python ×1

python-class ×1

python-decorators ×1