gpt4 book ai didi

python - Pandas 数据框到字典

转载 作者:太空宇宙 更新时间:2023-11-04 00:49:15 25 4
gpt4 key购买 nike

我有一个像这样的 Pandas 数据框:

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

需要来自上述数据框的字典,其中 COL1 将存储为键,value1 和 value2 将在子字典中。

例如:-

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

最佳答案

您可以使用 groupbyapply转换为 dict ziped 列并最后转换 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}}

关于python - Pandas 数据框到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37852436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com