繁体   English   中英

将函数应用于Pandas DataFrame的子类仅返回DataFrame,现在返回Subclass

[英]Applying function to subclass of Pandas DataFrame just returns DataFrame and now Subclass

我试图子类化熊猫的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中。 产生的丰度框架采用以下形式:

丰度样本

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

def apply_poisson_noise(self,keys=False):
    temp = self.copy()
    #print type(temp)
    if keys != False: 
        for key in keys:
            temp[key] = np.random.poisson(self[key])            
    else: 
        temp = self.apply(np.random.poisson)
    return temp

通过上面的内容,我可以创建一个AbundanceFrame,而不会出现问题。 但是,当我尝试apply_poisson_noise()时,它返回一个DataFrame而不是AbundanceFrame。 我一直在网上搜索,还没有找到一种将函数应用于大熊猫的DataFrames的方法。

我想知道如何拥有此功能并返回AbundanceFrame。

谢谢!

解决了问题:(基于user4589964的响应)在apply_poisson_noise()中,我仅调用AbundanceFrame构造函数并将其提供给计算的数据。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM