小编Mat*_*oll的帖子

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
查看次数

将整数列表分解为递增序列列表

假设列表中没有连续的整数。

我尝试使用 NumPy ( np.diff) 来计算每个元素之间的差异,但无法使用它来获得答案。下面是输入(第一行)和预期输出(第二行)的两个示例。

[6, 0, 4, 8, 7, 6]
[[6], [0, 4, 8], [7], [6]]


[1, 4, 1, 2, 4, 3, 5, 4, 0]
[[1, 4], [1, 2, 4], [3, 5], [4], [0]]
Run Code Online (Sandbox Code Playgroud)

python

2
推荐指数
1
解决办法
1248
查看次数

标签 统计

python ×2

pandas ×1

python-class ×1

python-decorators ×1