Reputation: 3667
I have two dataframes like so:
df1
colA colB
1 3
2 4
df2
colA colB
A C
B D
I want to create a dictionary object that will allow me to map new values from df1 and convert them to values for df2.
I am able to create the dictionary object between columns like so:
dict(zip(df1.colA.unique(),df2.colA.unique()))
This gives me the output:
{1:'A',2:'B'}
how do I do this for multiple columns to create a single large dictionary that will be used for converting new data?
I tried adding multiple columns like this:
dict(zip(df1.A.unique(),df2.A.unique(),df1.B.unique(),df2.B.unique()))
I get error:
ValueError: dictionary update sequence element #0 has length 4; 2 is required
Upvotes: 2
Views: 1513
Reputation: 75080
A dictionary can only have 1 key and 1 value, when you zip multiple columns like that, you are asking python 2 create more than 2 sequence element which isnt possible. You can instead create the first dict and update it with another like:
d=dict(zip(df1.colA.unique(),df2.colA.unique()))
d.update(dict(zip(df1.colB.unique(),df2.colB.unique())))
print(d)
{1: 'A', 2: 'B', 3: 'C', 4: 'D'}
Upvotes: 1