Why can't I apply shift from within a pandas function?

前端 未结 3 1789
陌清茗
陌清茗 2020-12-21 08:26

I am trying to build a function that uses .shift() but it is giving me an error. Consider this:

In [40]:

data={\'level1\':[20,19,20,21,25,29,30,31,30,29,31]         


        
3条回答
  •  轮回少年
    2020-12-21 09:03

    Try passing the frame to the function, rather than using apply (I am not sure why apply doesn't work, even column-wise):

    def f(x):
        x.level1 
        return x.level1 + x.level1.shift(1)
    
    f(frame)
    

    returns:

    2014-12-01   NaN
    2014-12-02    39
    2014-12-03    39
    2014-12-04    41
    2014-12-05    46
    2014-12-06    54
    2014-12-07    59
    2014-12-08    61
    2014-12-09    61
    2014-12-10    59
    2014-12-11    60
    Freq: D, Name: level1, dtype: float64
    

提交回复
热议问题