Expansion and explanation on my code version. Here we use the dataframe "apply" function to apply a function to the dataframe
import pandas as pd
def my_transform(x): #function to be applied to the dataframe
if x[0]>4: # refer to dataframe as "x". Test if first column is >4
return x[0] # if >4, return that value
else: #otherwise
return x[1] #return the value from the second column
df = pd.DataFrame(data=[[1,2,3],[4,5,6],[7,8,9]]) #create a simple dataframe with 3 rows and 3 columns
df[3] = df.apply(my_transform, axis=1) #calls the function above, apply "by row" rather than by column (axis value)
df #display result
Output:
0 1 2 3
0 1 2 3 2
1 4 5 6 5
2 7 8 9 7