Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 616
okuoub Avatar asked Feb 17 '20 14:02

okuoub


4 Answers

df['col1'] = df.apply(lambda x: x['col3'] if x['col1'] < x['col2'] else x['col1'], axis=1)
like image 81
Eric Yang Avatar answered Nov 10 '22 00:11

Eric Yang


The most eficient way is by using the loc operator:

mask = df["col1"] < df["col2"]
df.loc[mask, "col1"] = df.loc[mask, "col3"]
like image 7
villoro Avatar answered Nov 10 '22 01:11

villoro


df.loc[df["col1"] < 2, "col1"] = df["col3"]
like image 2
mkk Avatar answered Nov 10 '22 00:11

mkk


As mentioned by @anky_91 use np.where to update the 'col1' values:

df['col1'] = np.where(df['col1'] < df['col2'], df['col3'], df['col1'])
like image 2
ManojK Avatar answered Nov 10 '22 02:11

ManojK