Home > Back-end >  Pandas: Change value in another column by checking a list of values from different/another column
Pandas: Change value in another column by checking a list of values from different/another column

Time:08-03

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

CodePudding user response:

Use Series.isin:

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

CodePudding user response:

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
  • Related