0

I want to create a new column col2 and calculate using a Dictionary. When a key is not found, I want to calculate the value as 0:

import pandas as pd
df = pd.DataFrame({'col1': {0: 'a', 1: 'b', 2: 'c'}})
d = {'a':1,'b':2}
  col1
0    a
1    b
2    c

So I try:

df['col2'] = d.get(df['col1'], 0)
builtins.TypeError: 'Series' objects are mutable, thus they cannot be hashed

Im guessing I need to use map, like this: df['col2'] = df['col1'].map(d) But how to get 0 when a key is missing, and not Nan?

BERA
  • 864
  • 2
  • 12
  • 32

2 Answers2

2

Use map with fillna:

df['col2'] = [d.get(value, 0) for value in df['col1']]

OR:

df['col2'] = df['col1'].map(d).fillna(0, downcast='infer')

print(df)
  col1  col2
0    a     1
1    b     2
2    c     0
Space Impact
  • 12,342
  • 18
  • 44
0

Try this,

df['col2']=df['col1'].map(d).fillna(0)

O/P:

  col1  col2
0    a   1.0
1    b   2.0
2    c   0.0
Mohamed Thasin ah
  • 9,418
  • 9
  • 43
  • 83