Reputation: 3262
I have python dict like this:
keysdict={'date': {20: '201012', 21: '201101', 22: '201102', 23: '201103', 24: '201104', 25: '201105', 26: '201106', 27: '201107', 28: '201108', 29: '201109', 30: '201110', 31: '201111'}}
And I have pandas dataframe like this
A B
20 0.123
21 2.123
22 4.45
23 3.2
24 3.1
25 3.9
26 4.2
Now I want to add an extra column C
which takes the respective value from dict keys that are in Column A
. Like below one
A B C
20 0.123 201012
21 2.123 201101
22 4.45 201102
23 3.2 201103
24 3.1 201104
25 3.9 201105
26 4.2 201106
I tried this
df.loc[:,'C']=keysdict['date'][df.loc['A']]
But getting below error
KeyError: 'the label [A] is not in the [index]
Upvotes: 0
Views: 179
Reputation: 38415
You can directly use map without apply
df['C'] = df['A'].map(keysdict['date'])
A B C
0 20 0.123 201012
1 21 2.123 201101
2 22 4.450 201102
3 23 3.200 201103
4 24 3.100 201104
5 25 3.900 201105
6 26 4.200 201106
Upvotes: 3
Reputation: 7903
Try map instead:
df['C'] = df['A'].map(keysdict['date'])
If column 'A' is an index:
df['C'] = df.map(keysdict['date'])
Upvotes: 3
Reputation: 57033
df.loc['A']
refers to the row labeled 'A', and you need column, which is accessed as df['A']
. Here's the correct code:
df = pd.DataFrame({'A':[20,21,22,23], 'B':[0.123,2.123,4.45,3.2]})
# A B
#0 20 0.123
#1 21 2.123
#2 22 4.450
#3 23 3.200
Sample key dictionary:
keysdict = {'date' : {20:0,21:1,22:2,23:3}}
df['C'] = df['A'].apply(lambda x: keysdict['date'][x])
# A B C
#0 20 0.123 0
#1 21 2.123 1
#2 22 4.450 2
#3 23 3.200 3
Upvotes: 1