How to match previous row value in a same column using df.iterrows()?

Viewed 102

I am trying to match previous row value with a particular value using index number. But i don't know how to implement this. Could you please help me how to do this?

Example:

operator_type   Operator
    =            None
    =            AND
    =            None
    =            OR
    =            None
    =            None

code i am trying:

for index, row in df.iterrows():
       if row['Operator'] == None and row['operator_type'] == '=' and row['Operator'].(index-1).values != 'AND':
             print('alka')

Error:

File "imed_cons_new.py", line 68
    if row['and_or_not_oprtor'] == None and row['operator_type'] == '=' and row['and_or_not_oprtor'].(index-1).values != 'AND':
                                                                                                     ^
SyntaxError: invalid syntax
3 Answers

You should try "shift()"

df['previous'] = df['Operator'].shift()

for index, row in df.iterrows():
   if row['Operator'] == None and row['operator_type'] == '=' and row['previous'] != 'AND':
     print(index,'alka')

output:

0 alka
4 alka
5 alka

you can try a vectorized solution:

np.where((df['operator'].isna()) & (df['operator'].shift() != 'AND') & (df['operator_type'] == '='))[0]

The result:

pd.DataFrame({'type':'alka'}, 
             index=np.where((df['operator'].isna()) & (df['operator'].shift() != 'AND') & (df['operator_type'] == '='))[0])

OUT:
  type
0 alka
4 alka
5 alka

As the error says , it is just syntax errors. there are better ways to do what you are trying to do but for now just make the following change

   if row['Operator'] == None and row['operator_type'] == '=' and row['Operator'].(index-1).values != 'AND':

to

   if row['Operator'] == None and row['operator_type'] == '=' and row['Operator'][index-1]  != 'AND':
Related