从pandas.rolling_apply返回两个值

时间:2014-03-06 07:59:06

标签: python pandas

我正在使用pandas.rolling_apply将数据拟合到分布中并从中获取值,但我需要它还报告滚动的拟合优度(特别是p值)。目前我这样做:

def func(sample):
    fit = genextreme.fit(sample)
    return genextreme.isf(0.9, *fit)

def p_value(sample):
    fit = genextreme.fit(sample)
    return kstest(sample, 'genextreme', fit)[1]

values = pd.rolling_apply(data, 30, func)
p_values = pd.rolling_apply(data, 30, p_value)
results = pd.DataFrame({'values': values, 'p_value': p_values})

问题是我有很多数据,而且拟合函数很昂贵,所以我不想为每个样本调用两次。我宁愿做的是这样的事情:

def func(sample):
    fit = genextreme.fit(sample)
    value = genextreme.isf(0.9, *fit)
    p_value = kstest(sample, 'genextreme', fit)[1]
    return {'value': value, 'p_value': p_value}

results = pd.rolling_apply(data, 30, func)

结果是DataFrame,其中包含两列。如果我尝试运行它,我会得到一个例外: TypeError: a float is required。是否有可能实现这一目标,如果是,如何实现?

4 个答案:

答案 0 :(得分:3)

我有一个类似的问题,并通过在应用期间使用单独的助手类的成员函数来解决它。该成员函数根据需要返回单个值,但我将其他calc结果存储为类的成员,然后可以使用它。

简单示例:

class CountCalls:
    def __init__(self):
        self.counter = 0

    def your_function(self, window):
        retval = f(window)
        self.counter = self.counter + 1


TestCounter = CountCalls()

pandas.Series.rolling(your_seriesOrDataframeColumn, window = your_window_size).apply(TestCounter.your_function)

print TestCounter.counter

假设你的函数f将返回两个值为v1,v2的元组。然后,您可以返回v1并将其分配给column_v1到您的数据帧。第二个值v2只是在helper类中的Series series_val2中累积。之后,您只需将该系列作为数据框的新列。 JML

答案 1 :(得分:2)

之前我遇到过类似的问题。这是我的解决方案:

from collections import deque
class your_multi_output_function_class:
    def __init__(self):
        self.deque_2 = deque()
        self.deque_3 = deque()

    def f1(self, window):
        self.k = somefunction(y)
        self.deque_2.append(self.k[1])
        self.deque_3.append(self.k[2])
        return self.k[0]    

    def f2(self, window):
        return self.deque_2.popleft()   
    def f3(self, window):
        return self.deque_3.popleft() 

func = your_multi_output_function_class()

output = your_pandas_object.rolling(window=10).agg(
    {'a':func.f1,'b':func.f2,'c':func.f3}
    )

答案 2 :(得分:1)

我也有同样的问题。我通过生成一个全局数据框并从滚动功能中提供它来解决它。在以下示例脚本中,我生成随机输入数据。然后,我用一个滚动应用函数计算min,max和mean。

import pandas as pd
import numpy as np

global outputDF
global index

def myFunction(array):

    global index
    global outputDF

    # Some random operation
    outputDF['min'][index] = np.nanmin(array)
    outputDF['max'][index] = np.nanmax(array)
    outputDF['mean'][index] = np.nanmean(array)

    index += 1
    # Returning a useless variable
    return 0

if __name__ == "__main__":

    global outputDF
    global index

    # A random window size
    windowSize = 10

    # Preparing some random input data
    inputDF = pd.DataFrame({ 'randomValue': [np.nan] * 500 })
    for i in range(len(inputDF)):
        inputDF['randomValue'].values[i] = np.random.rand()


    # Pre-Allocate memory
    outputDF = pd.DataFrame({ 'min': [np.nan] * len(inputDF),
                              'max': [np.nan] * len(inputDF),
                              'mean': [np.nan] * len(inputDF)
                              })   

    # Precise the staring index (due to the window size)
    d = (windowSize - 1) / 2
    index = np.int(np.floor( d ) )

    # Do the rolling apply here
    inputDF['randomValue'].rolling(window=windowSize,center=True).apply(myFunction,args=())

    assert index + np.int(np.ceil(d)) == len(inputDF), 'Length mismatch'

    outputDF.set_index = inputDF.index

    # Optional : Clean the nulls
    outputDF.dropna(inplace=True)

    print(outputDF)

答案 3 :(得分:1)

我使用和喜爱@ yi-yu的答案,所以我把它变成了通用的:

from collections import deque
from functools import partial

def make_class(func, dim_output):

    class your_multi_output_function_class:
        def __init__(self, func, dim_output):
            assert dim_output >= 2
            self.func = func
            self.deques = {i: deque() for i in range(1, dim_output)}

        def f0(self, *args, **kwargs):
            k = self.func(*args, **kwargs)
            for queue in sorted(self.deques):
                self.deques[queue].append(k[queue])
            return k[0]

    def accessor(self, index, *args, **kwargs):
        return self.deques[index].popleft()

    klass = your_multi_output_function_class(func, dim_output)

    for i in range(1, dim_output):
        f = partial(accessor, klass, i)
        setattr(klass, 'f' + str(i), f)

    return klass

并且给出了pandas系列的函数f(窗口但不一定)返回n值,您可以这样使用它:

rolling_func = make_class(f, n)
# dict to map the function's outputs to new columns. Eg:
agger = {'output_' + str(i): getattr(rolling_func, 'f' + str(i)) for i in range(n)} 
windowed_series.agg(agger)