Vinay Ranjan
Vinay Ranjan

Reputation: 294

Pandas dataframe to dictionary

I have a pandas dataframe like :

COL1 VALUE1 VALUE2
 A      A12     1    
 B      B13     2 
 A      C12     3
 B      Q12     4

Need a dictionary from the above dataframe where COL1 will be stored as the key and value1 and value2 will be in sub-dict.

eg:-

dict = {'A':{'A12':1, 'C12':3}, B:{'B13':2, 'Q12':4}}

Upvotes: 2

Views: 121

Answers (1)

jezrael
jezrael

Reputation: 862511

You can use groupby with apply converted to dict ziped columns and last convert to_dict:

d = df.groupby('COL1').apply(lambda x: dict(zip(x.VALUE1, x.VALUE2))).to_dict()
print (d)
{'A': {'C12': 3, 'A12': 1}, 'B': {'B13': 2, 'Q12': 4}}

Upvotes: 3

Related Questions