I have a dataframe like
Sr.No ID A B C D
1 Tom Earth English BMW
2 Tom Mars Spanish BMW
You can use groupby
with orient of to_dict as list
and convert the resultant series to a dictionary
.
df.set_index('Sr.No', inplace=True)
df.groupby('ID').apply(lambda x: x.to_dict('list')).reset_index(drop=True).to_dict()
{0: {'C': ['Mercedes', 'Audi'], 'ID': ['John', 'John'], 'A': ['Venus', nan],
'B': ['Portugese', 'German'], 'D': ['Blue', 'Red']},
1: {'C': ['Audi'], 'ID': ['Michael'], 'A': ['Mercury'], 'B': ['Hindi'], 'D': ['Yellow']},
2: {'C': ['BMW', 'BMW'], 'ID': ['Tom', 'Tom'], 'A': ['Earth', 'Mars'],
'B': ['English', 'Spanish'], 'D': [nan, 'Green']}}
Inorder to remove ID
, you can also do:
df.groupby('ID')['A','B','C','D'].apply(lambda x: x.to_dict('list')) \
.reset_index(drop=True).to_dict()