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
  • 1,345
  • 3
  • 16
  • 36

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
  • 13,085
  • 23
  • 48
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
  • 10,754
  • 11
  • 52
  • 111