Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fill pandas dataframe from multiple dicts

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading