please advise how optimal solve the following task:
I have pandas dataframe:
1st | 2nd | 3rd |
---|---|---|
1 | 8 | 10 |
2 | 1 | 0 |
5 | 1 | 0 |
1 | 3 | 0 |
df.shape is (100,3). 1st column values from 0 to 5, 2nd: 0-8, 3rd: 0-10
and 3 dicts with different key:values.
dict1 = {0: 'a',
1: 'b', ..., 5: 'xx'}
dict2 = {0: 'aa',
1: 'bb', ..., 8: 'yy'}
dict2 = {0: 'aaa',
1: 'bbb', ..., 10: 'zzz'}
the question is how to replace values in dataframe by keys from dicts?
something like that but for all columns:
df['1st'].map({v: k for v, k in enumerate(dict1)}).to_frame()
CodePudding user response:
Use zip
with Series.map
for columns in list:
dict1 = {0: 'a', 1: 'b', 3:'r',2:'y', 5: 'xx'}
dict2 = {0: 'aa',6:'ww', 1: 'bb', 8: 'yy'}
dict3 = {0: 'aaa', 3:'ree',5:'eey', 1: 'bbb', 10: 'zzz'}
for c, d in zip(['1st', '2nd', '3rd'], [dict1, dict2, dict3]):
df[c] = df[c].map(d)
print (df)
1st 2nd 3rd
0 b bb zzz
1 b ww ree
2 r yy eey
3 xx bb eey
4 y bb zzz
5 xx bb bbb