将函数应用于Pandas DataFrame的子类只返回DataFrame和now子类

2024-03-29 10:07:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试子类Pandas的DataFrame对象。

class AbundanceFrame(pd.DataFrame):
   'Subclass of DataFrame used for creating simulated dataset with various component timeseries'

    def __init__(self, days,*args,**kw):
        'Constructor for AbundanceFrame class, must pass index of timeseries'
        super(AbundanceFrame,self).__init__(index = days,*args,**kw)
        self.steps = 0
        self.monotonic = 0

我有许多其他的方法,可以将模拟的时间序列添加到结果的丰度框架中。由此产生的丰度框架呈现以下形式:

AbundanceFrame-Sample

然后我想对丰度帧中的所有数据应用泊松采样噪声。

^{pr2}$

有了以上我可以创建一个丰富的框架没有问题。但是,当我尝试应用_poisson_noise()时,它返回一个DataFrame而不是一个bundianceframe。我一直在网上搜索,但还没有找到一种方法将函数应用于pandas的数据帧。

我想知道我如何能有这个功能和返回一个丰盛框架。

谢谢你!


Tags: of数据方法self框架dataframeforindex
1条回答
网友
1楼 · 发布于 2024-03-29 10:07:45

解决了问题:(基于用户4589964的响应) 在apply_poisson_noise()中,我只调用bundianceFrame构造函数,并将计算的数据提供给它。在

from copy import deepcopy

class AbundanceFrame(pd.DataFrame):
'Subclass of DataFrame used for creating simulated dataset with various component timeseries'

def __init__(self, days,steps=0,monotonic=0,*args,**kw):
    'Constructor for AbundanceFrame class, must pass index of timeseries'
    super(AbundanceFrame,self).__init__(index = days,*args,**kw)
    self.steps = steps
    self.monotonic = monotonic

def apply_poisson_noise(self,keys=False):
    temp = deepcopy(self)
    if keys != False: 
        for key in keys:
            temp[key] = np.random.poisson(self[key])  
        temp =  AbundanceFrame(self.index, columns=self.columns, data = temp.values,
                               steps=self.steps, monotonic=self.monotonic)
    else: 
        temp =  AbundanceFrame(self.index, columns=self.columns, data = self.apply(np.random.poisson),
                               steps=self.steps, monotonic=self.monotonic)
    return temp

相关问题 更多 >