vendredi 10 juin 2016

apply/ map function to prior row


still new to functions and its application I would like to create a new column D for a dataframe:

 df = pd.DataFrame([[1, 2, 3], [1, 3, 5], [4, 6, 7]], columns=['A', 'B', 'C'])

    A   B   C
 0  1   2   3
 1  1   3   5
 2  4   6   7

the column D and its content shall be created by the help of a function, I though about this fashion:

 def my_func(B, C):
     if C > B.shift(1):
         df['D'] = 'right'
     return df['D']
 else:
      df['D'] = 'left'
      return df['D']

So in plain words: if the value in C is higher than the value of B from the previous row than the cell gets 'right', else 'left'. I do not get it to run, somehow the shift is not accepted or I get the error message

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Any help welcome on how best use functions for such a task and also apply shift().


Aucun commentaire:

Enregistrer un commentaire