Skip to content Skip to sidebar Skip to footer

Map Two Data Frames To Create A Dictionary With Multiple Values For A Key - Pandas

I want to create a dictionary that will have multiple values for a key. I have the following DataFrame df1 like this: ID SUM COUNT 2 3002 256401.0 15 1 3

Solution 1:

Let try this on df2:

df2.set_index('ID')[['Var1','Var2','Var3']].stack().groupby(level=0).apply(lambda x: x.unique()).to_dict()

Output:

    {3021: array(['Cfd45', 'shkjs', 'sfs', 'None', 'fjslk', 'hjfks', 'shka', 'fsad'], dtype=object),
 3022: array(['None', 'skank', 'vssf', 'sdkj', 'vbjajl', 'bbf'], dtype=object),
 3025: array(['klgf', 'vcbj', 'jgjg'], dtype=object),
 3026: array(['tuo', 'None', 'gdsfs', 'klo', 'ahk', 'nbjd', 'alkdjl', 'sfsfs'], dtype=object)}

OR

df2.set_index('ID')[['Var1','Var2','Var3']].stack().groupby(level=0).apply(lambda x: x.unique()).to_json()

Output:

'{"3021":["Cfd45","shkjs","sfs","None","fjslk","hjfks","shka","fsad"],"3022":["None","skank","vssf","sdkj","vbjajl","bbf"],"3025":["klgf","vcbj","jgjg"],"3026":["tuo","None","gdsfs","klo","ahk","nbjd","alkdjl","sfsfs"]}'

Post a Comment for "Map Two Data Frames To Create A Dictionary With Multiple Values For A Key - Pandas"