j. DOE
j. DOE

Reputation: 278

Compare two values in the same column python

I'm trying to compare two values in the same column in a pandas.DataFrame.
If the two values are different I want to create a new value. My code looks like this:

def f(x, var1, var2):
            if (x[var1].shift(1) != x[var1]):
                x[var2] = 1
            else:
                x[var2] = 0
            return x  

sdf['2008':'2009'].apply(lambda x: f(x, 'ROW1','ROW2'),axis = 1)

Unfortunatly, this one doesn't work. I get the following error massage

'numpy.float64' object has no attribute 'shift'", 'occurred at index 2008-01-01 00:00:00'

Thanks for your help.

Upvotes: 0

Views: 460

Answers (1)

Sociopath
Sociopath

Reputation: 13401

I think you need:

df0 = df.shift()

df['Row2'] = np.where(df0['Row1']!=df['Row1'], 1, 0)

EDIT:

As @jpp suggested in comments:

df['Row2'] = (df0['Row1']!=df['Row1']).astype(int)

Upvotes: 1

Related Questions