Legolas
Legolas

Reputation: 773

Python: rolling.apply() gives TypeError

My function:

def f(x):
    print(len(x)) 
    return

test.set_index('exchTstamp',inplace=True)
test['fit_x'].rolling('1.0S').apply(lambda x: f(list(x)))

On running below code on a time-indexed dataframe, I am getting the following error:

> TypeError                                 Traceback (most recent call
> last) <ipython-input-151-4de6334ec332> in <module>()
> ----> 1 g=testTbt['fit_x'].rolling('1.0S').apply(lambda x: f(list(x)))
> 
> /usr/lib64/python2.7/site-packages/pandas/core/window.pyc in
> apply(self, func, raw, args, kwargs)    1701     def apply(self, func,
> raw=None, args=(), kwargs={}):    1702         return super(Rolling,
> self).apply(
> -> 1703             func, raw=raw, args=args, kwargs=kwargs)    1704     1705     @Substitution(name='rolling')
> 
> /usr/lib64/python2.7/site-packages/pandas/core/window.pyc in
> apply(self, func, raw, args, kwargs)    1010     1011         return
> self._apply(f, func, args=args, kwargs=kwargs,
> -> 1012                            center=False, raw=raw)    1013     1014     def sum(self, *args, **kwargs):
> 
> /usr/lib64/python2.7/site-packages/pandas/core/window.pyc in
> _apply(self, func, name, window, center, check_minp, **kwargs)
>     878                     result = np.apply_along_axis(calc, self.axis, values)
>     879                 else:
> --> 880                     result = calc(values)
>     881 
>     882             if center:
> 
> /usr/lib64/python2.7/site-packages/pandas/core/window.pyc in calc(x)
>     872                 def calc(x):
>     873                     return func(x, window, min_periods=self.min_periods,
> --> 874                                 closed=self.closed)
>     875 
>     876             with np.errstate(all='ignore'):
> 
> /usr/lib64/python2.7/site-packages/pandas/core/window.pyc in f(arg,
> window, min_periods, closed)    1007             return
> libwindow.roll_generic(    1008                 arg, window, minp,
> indexi,
> -> 1009                 closed, offset, func, raw, args, kwargs)    1010     1011         return self._apply(f, func, args=args,
> kwargs=kwargs,
> 
> pandas/_libs/window.pyx in pandas._libs.window.roll_generic()
> 
> TypeError: a float is required

I basically want to do some calculations on a rolling base, like calculating the exponential moving average. Please let me know where I'm going wrong.

Data can be found here

Upvotes: 0

Views: 156

Answers (1)

Emil Vatai
Emil Vatai

Reputation: 2531

It seems you'd want to have the function f to return a value. apply is similar to map and it needs to return a value.

Upvotes: 1

Related Questions