I have a dictionary with multiple values for 1 key. Now, I need to map them with the dataframe column. Any idea how can I solve this?
Dictionary
Keys_nd_Values = {'ABCD' : [223, 343, 432], 'ZXS' : ['S23', 'GT4','98J']}
Data
A B C 12525 1FWE23 223 14654 14654 S23 24798 24798 223 38945 38945 223 46456 46485 GT4 AD545 45346 98J A5D66 A5D66 432
Expected
A B C 12525 1FWE23 ABCD 14654 14654 ZXS 24798 24798 ABCD 38945 38945 ABCD 46456 46485 ZXS AD545 45346 ZXS A5D66 A5D66 ABCD
Advertisement
Answer
First we convert the Keys_nd_Values to a df and convert the rows to columns. The function we wrote later does this: get the value of the column if the row value exists as a column in the df named control.
dfx=pd.DataFrame(Keys_nd_Values) control = dfx.melt(ignore_index = False).set_index('value').T 223 343 432 S23 GT4 98J variable ABCD ABCD ABCD ZXS ZXS ZXS def check(a): if a in control.columns.to_list(): return control[a][0] else: return a for i in df1.columns: df1[i]=df1[i].apply(check) print(df1) A B C 0 12525 1FWE23 ABCD 1 14654 14654 ZXS 2 24798 24798 ABCD 3 38945 38945 ABCD 4 46456 46485 ZXS 5 AD545 45346 ZXS 6 A5D66 A5D66 ABCD