Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change column value based on multiple conditions

Tags:

pandas

I've seen a lot of posts similar but none seem to answer this question:

I have a data frame with multiple columns. Lets say A, B and C

I want to change column A's value based on conditions on A, B and C

I've got this so far but not working.

df=df.loc[(df['A']=='Harry') 
                   & (df['B']=='George') 
                   & (df['C']>'2019'),'A']=='Matt'

So if A is equal to Harry, and B is equal to George and C is greater than 2019, then change A to Matt

Anyone see what I've done wrong?

like image 958
fred.schwartz Avatar asked Nov 21 '18 11:11

fred.schwartz


People also ask

How do you change the values of a column in pandas based on multiple condition?

You can replace values of all or selected columns based on the condition of pandas DataFrame by using DataFrame. loc[ ] property. The loc[] is used to access a group of rows and columns by label(s) or a boolean array. It can access and can also manipulate the values of pandas DataFrame.

How do I change the value of a column based on a condition?

To do a conditional update depending on whether the current value of a column matches the condition, you can add a WHERE clause which specifies this. The database will first find rows which match the WHERE clause and then only perform updates on those rows.


1 Answers

You are really close, assign value Matt to filtered A by boolean masks:

df.loc[(df['A']=='Harry') & (df['B']=='George') & (df['C']>'2019'),'A'] = 'Matt'
like image 170
jezrael Avatar answered Sep 23 '22 13:09

jezrael