Python 从数据帧到字典

Python 从数据帧到字典,python,dictionary,pandas,group-by,Python,Dictionary,Pandas,Group By,我有一个数据框,如: COL1 VALUE1 VALUE2 A A12 1 B B13 2 A C12 3 B Q12 4 需要上述数据框中的字典,其中COL1将存储为键,value1和value2将存储在sub-dict中 例如:- 您可以与转换为dictziped列和上次转换一起使用: dict = {'A':{'A12':1, 'C12':3}, B:{'B13':2, 'Q12':4}} d =

我有一个数据框,如:

COL1 VALUE1 VALUE2
 A      A12     1    
 B      B13     2 
 A      C12     3
 B      Q12     4
需要上述数据框中的字典,其中COL1将存储为键,value1和value2将存储在sub-dict中

例如:-

您可以与转换为
dict
zip
ed列和上次转换一起使用:

dict = {'A':{'A12':1, 'C12':3}, B:{'B13':2, 'Q12':4}}
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}}