Issue
import pandas as pd
data={'col1':[1,3,3,1,2,3,2,2]}
df=pd.DataFrame(data,columns=['col1'])
print df
col1
0 1
1 3
2 3
3 1
4 2
5 3
6 2
7 2
I have the following Pandas DataFrame and I want to create another column that compares the previous row of col1 to see if the value of the row is greater than that of the previous row. It should come out like the following:
col1 match
0 1 False
1 3 False
2 3 True
3 1 False
4 2 False
5 3 True
6 2 False
7 2 True
Thank you.
Solution
Compare shifted values by Series.gt
and Series.shift
,last missing value is replaced to -1
for True
, working, if all values are positive:
df['match'] = df['col1'].gt(df['col1'].shift(-1, fill_value=-1))
print (df)
col1 match
0 1 False
1 3 False
2 3 True
3 1 False
4 2 False
5 3 True
6 2 False
7 2 True
If need last value set to True
for any Dataframe:
df['match'] = df['col1'].gt(df['col1'].shift(-1))
df.loc[df.index[-1], 'match'] = True
Answered By – jezrael
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0