Python dataframe: how to map a new column from existing column

Viewed 1886

I have a dataframe in which one columns have 4 different values such as 100, 200, 300 and 400. I want to create a new column that:

  • For 100, it becomes 25
  • For 200, it becomes 30
  • For 300 it becomes 33
  • For 400 it becomes43... etc...

How can I do it without looping?

1 Answers

You can use a dictionary with pd.Series.map:

df = pd.DataFrame({'A': [100, 400, 200, 300, 400, 200]})

d = {100: 25, 200: 30, 300: 33, 400: 43}
df['B'] = df['A'].map(d)

print(df)

     A   B
0  100  25
1  400  43
2  200  30
3  300  33
4  400  43
5  200  30

Unmapped values will give NaN. If you wish to keep unmapped values as they are you can fillna afterwards:

df['B'] = df['A'].fillna(df['B']).astype(int)
Related