I have a column in a dataframe which contains an array of numbers from 1 to 5 and I have an array containing five words. I would like to find the simplest, most compact and most elegant way in Python to “in place” replace the numbers in the column with the corresponding words. For example:
JavaScript
x
23
23
1
import pandas as pd
2
3
# This is the dataframe
4
df = pd.DataFrame({'code': ['A', 'B', 'C', 'D', 'E'], 'color': [4, 1, 2, 5, 1]})
5
6
# code color
7
# 0 A 4
8
# 1 B 1
9
# 2 C 2
10
# 3 D 5
11
# 4 E 1
12
13
# This is the array
14
colors = ["blue", "yellow", "red", "white", "black"]
15
16
# This is what I wish to obtain
17
# code color
18
# 0 A white
19
# 1 B blue
20
# 2 C yellow
21
# 3 D black
22
# 4 E blue
23
I am certain that the numbers in columns “color” are not NaN or outside range [1,5]. No check is necessary. Any suggestion?
Advertisement
Answer
This should do
JavaScript
1
2
1
df['color'] = df['color'].apply(lambda c: colors[c-1])
2