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
函数中引用上一行的值。
答案 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"})