Search code examples
pythonpandasdata-sciencedata-munging

pandas copy value from one column to another if condition is met


I have a dataframe:

df = 
col1  col2  col3 
1      2     3
1      4     6
3      7     2

I want to edit df, such that when the value of col1 is smaller than 2 , take the value from col3.

So I will get:

new_df = 
col1  col2  col3 
3      2     3
6      4     6
3      7     2

I tried to use assign and df.loc but it didn't work.

What is the best way to do so?


Solution

  • df['col1'] = df.apply(lambda x: x['col3'] if x['col1'] < x['col2'] else x['col1'], axis=1)