繁体   English   中英

从 dataframe 创建一个嵌套字典,其中第一列是父字典的键

[英]create a nested dictionary from dataframe, where first column is the key for parent dictionary

我正在尝试从 pandas dataframe 创建一个嵌套字典。第一列值应该是上部字典的键,它将包含其他列作为字典,其中列 header 是键。 我想避免循环。

dataframe:

df = pd.DataFrame({'A': [11, 11, 11, 11, 11, 11, 12, 12],
                   'B': [1, 2, 3, 1, 2, 3, 4, 5],
                   'C': [1.0, 0.7, 0.3, 1.0, 0.7, 0.3, 1.0, 1.0]})

我想要什么:

dict_expt = {'11': {'B': [1, 2, 3],
                  'C': [1.0, 0.7, 0.3]},
           '12': {'B': [4, 5],
                  'C': [1.0]}}

我试过的:

df.groupby(['A']).agg({'B':lambda x: list(x.unique()),
                      'C':lambda x: list(x.unique())}).to_dict()

不幸的是返回:

{'B': 
     {11: [1, 2, 3], 
      12: [4, 5]}, 
'C': {11: [1.0, 0.7, 0.3], 
      12: [1.0]}}

非常感谢任何帮助。 谢谢

你很接近,只需将"index"添加到to_dict()

df.groupby(['A']).agg({'B':lambda x: list(x.unique()),
                      'C':lambda x: list(x.unique())}).to_dict("index")

Output:

{11: {'B': [1, 2, 3], 'C': [1.0, 0.7, 0.3]}, 12: {'B': [4, 5], 'C': [1.0]}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM