Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing Pandas column value if multiple conditions are met

I am trying to check a pandas row to see if two conditions are met, if these conditions are met I am changing on of the values of the dataframe.

import pandas as pd

d = {"age": [10, 20, 40, 20, 30, 20], "job": ["teacher", "teacher", "chef", "teacher", "doctor", "lifeguard"]}

df = pd.DataFrame(data=d)
print(df.head())
print("-"*20)

#mask = df[df["age"] == 20 and df["job"] == "teacher"]
df.loc[df["age"] == 20 and df["job"] == "teacher"] = "REPLACED!"
print(df.head())

I thought I would be able to make a boolean mask with the commented out section, but was unable to do so.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is a common error. You’re doing two things wrong:

  1. With pandas masks, you use & instead of and, and | instead of or
  2. & and | have a higher precedence than ==, so you need to wrap the x == y expression in parentheses:
df.loc[(df["age"] == 20) & (df["job"] == "teacher")] = "REPLACED!"

Output:

>>> df
         age        job
0         10    teacher
1  REPLACED!  REPLACED!
2         40       chef
3  REPLACED!  REPLACED!
4         30     doctor
5         20  lifeguard

Note that if you dislike wrapping the x == y expressions in parentheses, you can use x.eq(y) (which is pandas-specific):

df.loc[df["age"].eq(20) & df["job"].eq("teacher")] = "REPLACED!"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading