从数据帧创建嵌套字典,其中第一列是父字典的键

问题描述 投票:0回答:1

我正在尝试从pandas数据框创建嵌套字典。第一个列值应该是上级词典的键,它将污染其他列作为词典,其中列标题是键。我想避免循环。

数据框:

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': [1, 2],
                  'C': [1.0, 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]}}

非常感谢您的帮助。谢谢

python pandas dataframe dictionary
1个回答
1
投票

您已经关闭,只需将"index"添加到to_dict()

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

输出:

{11: {'B': [1, 2, 3], 'C': [1.0, 0.7, 0.3]}, 12: {'B': [4, 5], 'C': [1.0]}}
© www.soinside.com 2019 - 2024. All rights reserved.