【问题标题】:Applying function to subclass of Pandas DataFrame just returns DataFrame and now Subclass将函数应用于 Pandas DataFrame 的子类只返回 DataFrame 和现在的子类
【发布时间】:2015-02-23 23:39:39
【问题描述】:

我正在尝试继承 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 中。生成的 Abundance 框架采用以下形式:

然后我想将泊松采样噪声应用于丰度框架中的所有数据。

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 的方法,用于 pandas。

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

谢谢!

【问题讨论】:

    标签: python inheritance pandas subclass


    【解决方案1】:

    已解决问题:(基于 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-14
      • 2018-02-23
      • 1970-01-01
      • 2021-06-06
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多