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

Pandas: Change value in another column by checking a list of values from different/another column

i am trying to check for a column("Class") value to be matching any value set and if True then change value of different column name ("Measure") to 0 for that "Class" . In below example if values of column("Class") is any of [A,F,E] then change value in column named "Measure" to 0

        Name    Class   Measure
0      Fruit     A      34.0
1      Distance  B      4.0
2      Weight    F      0.6
3      Weight    E      2.0
4      Fruit     B      12.0
5      Fruit     D      42.0

I tried below but as you see it’s only 1 value check but i want a list of values(from column "Class" say [‘A’, ‘B’, ‘D’]

import pandas as pd
import numpy as np

df.Measure = np.where(df.Class.eq('A'),0, df.Measure)

Thanks in advance

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 :

Use isin and boolean indexing (no need for numpy.where, which will be slower here):

target = ['A','F','E'] 
df.loc[df['Class'].isin(target), 'Measure'] = 0

modified df:

       Name Class  Measure
0     Fruit     A      0.0
1  Distance     B      4.0
2    Weight     F      0.0
3    Weight     E      0.0
4     Fruit     B     12.0
5     Fruit     D     42.0
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