Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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().

EDIT: I am looking for a "function version" of the solution because this shall be a procedure that shall frequently be used.

like image 427
Al_Iskander Avatar asked Aug 04 '26 10:08

Al_Iskander


1 Answers

You can use numpy.where:

df['D'] = np.where(df.C > df.B.shift(), 'left', 'right')
print (df)
   A  B  C      D
0  1  2  3  right
1  1  3  5   left
2  4  6  7   left

If need function:

def f(B, C):
    df['D'] = np.where(C > B.shift(), 'left', 'right')
    return df

print(f(df.B, df.C))
   A  B  C      D
0  1  2  3  right
1  1  3  5   left
2  4  6  7   left

Or:

def f(B, C):
    df['D'] = np.where(C > B.shift(), 'left', 'right')
    return df.D

print(f(df.B, df.C))
0    right
1     left
2     left
Name: D, dtype: object
like image 83
jezrael Avatar answered Aug 06 '26 00:08

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!