从一个 pandas 功能,为什么我不能申请转变? [英] Why can't I apply shift from within a pandas function?

查看:313
本文介绍了从一个 pandas 功能,为什么我不能申请转变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图构建一个使用.shift()的函数,但它给我一个错误。 试想一下:

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],
      'level2': [10,10,20,20,20,10,10,20,20,10,10]}
index= pd.date_range('12/1/2014', periods=11)
frame=DataFrame(data, index=index)
frame

Out[40]:
            level1 level2
2014-12-01  20  10
2014-12-02  19  10
2014-12-03  20  20
2014-12-04  21  20
2014-12-05  25  20
2014-12-06  29  10
2014-12-07  30  10
2014-12-08  31  20
2014-12-09  30  20
2014-12-10  29  10
2014-12-11  31  10

一个正常功能工作正常。为了证明我计算同样的结果两次,使用直接和功能的方法:

A normal function works fine. To demonstrate I calculate the same result twice, using the direct and function approach:

In [63]:
frame['horizontaladd1']=frame['level1']+frame['level2']#works

def horizontaladd(x):
    test=x['level1']+x['level2']
    return test
frame['horizontaladd2']=frame.apply(horizontaladd, axis=1)
frame
Out[63]:
            level1 level2 horizontaladd1 horizontaladd2
2014-12-01  20  10  30  30
2014-12-02  19  10  29  29
2014-12-03  20  20  40  40
2014-12-04  21  20  41  41
2014-12-05  25  20  45  45
2014-12-06  29  10  39  39
2014-12-07  30  10  40  40
2014-12-08  31  20  51  51
2014-12-09  30  20  50  50
2014-12-10  29  10  39  39
2014-12-11  31  10  41  41

不过,虽然直接申请转移工作,在一个函数这是行不通的:

But while directly applying shift works, in a function it doesn't work:

frame['verticaladd1']=frame['level1']+frame['level1'].shift(1)#works

def verticaladd(x):
    test=x['level1']+x['level1'].shift(1)
    return test
frame.apply(verticaladd)#error

结果

KeyError: ('level1', u'occurred at index level1')

我也试过申请单列,这使得更多的意义在我的脑海里,但没有运气:

I also tried applying to a single column which makes more sense in my mind, but no luck:

def verticaladd2(x):
    test=x-x.shift(1)
    return test
frame['level1'].map(verticaladd2)#error, also with apply

错误:

AttributeError: 'numpy.int64' object has no attribute 'shift'

为什么不直接打电话转型呢?我需要将它嵌入到一个函数来计算多个列的同时,沿轴1。请参阅相关的问题<一href="http://stackoverflow.com/questions/28255734/how-to-create-interdependent-columns-in-pandas-part-1-ambiguous-truth-value-wi">How在大熊猫创造相互依存的列,第1部分:暧昧的真值与布尔逻辑

推荐答案

尝试使用适用(我不知道该帧传递给函数,而不是为什么适用不能正常工作,甚至列方式):

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)

收益:

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

这篇关于从一个 pandas 功能,为什么我不能申请转变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆