从pandas apply()函数中获取前一行值

时间:2014-01-29 01:11:07

标签: python pandas

import pandas as pd

def greater_or_less(d):
    if d['current'] > d['previous']:
        d['result']="Greater"
    elif d['current'] < d['previous']:
        d['result']="Less"
    elif d['current'] == d['previous']:
        d['result']="Equal"
    else:
        pass
    return d

df=pd.DataFrame({'current':[1,2,2,8,7]})

# Duplicate the column with shifted values
df['previous']=df['current'].shift(1)

df['result']=""

df=df.apply(greater_or_less,axis=1)

结果是:

   current  previous   result
        1       NaN         
        2         1  Greater
        2         2    Equal
        8         2  Greater
        7         8     Less

然后我会删除previous列,因为它不再需要了。结束时:

   current   result
        1         
        2  Greater
        2    Equal
        8  Greater
        7     Less

如何在不添加额外列的情况下执行此操作?

我想知道如何在greater_or_less函数中引用上一行的值。

1 个答案:

答案 0 :(得分:3)

使用diff()方法:

import pandas as pd
import numpy as np
df=pd.DataFrame({'current':[1,2,2,8,7]})
np.sign(df.current.diff()).map({1:"Greater", 0:"Equal", -1:"Less"})