从 pandas 内部获取上一行值apply()函数 [英] Getting previous row values from within pandas apply() function

查看:165
本文介绍了从 pandas 内部获取上一行值apply()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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列,因为它不再需要了.结束于:

I'd then drop the previous column as it's no longer needed. Ending up with:

   current   result
        1         
        2  Greater
        2    Equal
        8  Greater
        7     Less

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

How can I do this without adding the extra column?

我想做的是知道如何从greater_or_less函数中引用上一行的值.

What i'd like to do, is know how to reference the previous row's value from within the greater_or_less function.

推荐答案

使用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"})

这篇关于从 pandas 内部获取上一行值apply()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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