0

I want to replace the values in a pandas dataframe if they are contained in a set. Here is a mini-example:

lset = frozenset((0,1))
data = {'col1': [3, 2, 1, 0]}
df = pd.DataFrame.from_dict(data)

I want all the values of col1 contained in lset to be replaced by -5. The result would be equivalent to:

data = {'col1': [3, 2, -5, -5]}
df = pd.DataFrame.from_dict(data)

I tried

df.loc[df['col1'] in lset, 'col1'] = -5

but I'm getting TypeError: unhashable type: 'Series'

Nick stands with Ukraine
  • 2,634
  • 2
  • 32
  • 39

2 Answers2

1

Check with isin

df.loc[df['col1'].isin(lset), 'col1'] = -5
df
Out[180]: 
   col1
0     3
1     2
2    -5
3    -5
BENY
  • 296,997
  • 19
  • 147
  • 204
1

Use isin in a conditional np.where

df['col2']=np.where(df['col1'].isin(lset),-5,df['col1'])



   col1  col2
0     3     3
1     2     2
2     1    -5
3     0    -5
wwnde
  • 22,093
  • 5
  • 13
  • 27