I have created the following pandas dataframe:
import pandas as pd
ds = {'col1':[1,2,2,2,5,1,2,5,6,7]}
df = pd.DataFrame(data=ds)
The dataframe look like this:
print(df)
col1
0 1
1 2
2 2
3 2
4 5
5 1
6 2
7 5
8 6
9 7
I have then created the following dictionary:
dict = {
1 : 'A',
2 : 'B',
3 : 'C',
4 : 'D',
5 : 'E',
6 : 'F',
7 : 'G',
8 : 'H',
9 : 'I',
10 : 'J'
}
I need to create a new column (called col2
) which results from applying the data dictionary to col1
.
I have tried this code:
df['col2'] = dict[df['col1']]
print(df)
But I get this error:
df['col2'] = dict[df['col1']]
TypeError: unhashable type: 'Series'
A solution could be to iterate through each and every row, but that would be very inefficient. Is there a pythonic way to apply the dictionary so to get the following dataframe?
col1 col2
0 1 A
1 2 B
2 2 B
3 2 B
4 5 E
5 1 A
6 2 B
7 5 E
8 6 F
9 7 G