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
JavaScript
x
3
1
Keys_nd_Values = {'ABCD' : [223, 343, 432],
2
'ZXS' : ['S23', 'GT4','98J']}
3
Data
JavaScript
1
9
1
A B C
2
12525 1FWE23 223
3
14654 14654 S23
4
24798 24798 223
5
38945 38945 223
6
46456 46485 GT4
7
AD545 45346 98J
8
A5D66 A5D66 432
9
Expected
JavaScript
1
9
1
A B C
2
12525 1FWE23 ABCD
3
14654 14654 ZXS
4
24798 24798 ABCD
5
38945 38945 ABCD
6
46456 46485 ZXS
7
AD545 45346 ZXS
8
A5D66 A5D66 ABCD
9
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.
JavaScript
1
26
26
1
dfx=pd.DataFrame(Keys_nd_Values)
2
control = dfx.melt(ignore_index = False).set_index('value').T
3
4
223 343 432 S23 GT4 98J
5
variable ABCD ABCD ABCD ZXS ZXS ZXS
6
7
def check(a):
8
if a in control.columns.to_list():
9
return control[a][0]
10
else:
11
return a
12
13
for i in df1.columns:
14
df1[i]=df1[i].apply(check)
15
16
print(df1)
17
A B C
18
0 12525 1FWE23 ABCD
19
1 14654 14654 ZXS
20
2 24798 24798 ABCD
21
3 38945 38945 ABCD
22
4 46456 46485 ZXS
23
5 AD545 45346 ZXS
24
6 A5D66 A5D66 ABCD
25
26