3
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.

1 Answer 1

1

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
    
Sign up to request clarification or add additional context in comments.

5 Comments

Is it only work with gt? or the operator >= would work too?
Thank you for your prompt reply. Another quick question here: what if I want to compare row values with custom operations? Say print "True" if the value of a row is greater than that of the previous row by 20%?
@adirabargil - gt is like >, for => is used ge
@NovaPoi - 20% Do you need 20% from values and compare? Not understand, I think it should be new question.
@NovaPoi - or need df['match'] = df['col1'].gt(df['col1'].mul(0.2).shift(-1, fill_value=-1)) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.