【问题标题】:Multi-level dictionary structure from DataFrame来自 DataFrame 的多级字典结构
【发布时间】:2020-10-29 04:03:49
【问题描述】:

我想从 DataFrame 中创建一个具有特定数据格式的多层字典。

通用输入,日期为字符串(不可变):

cleaned['Date'] = cleaned['Date'].astype(str)
cleaned.tail(3)

对应的输出:

Date          Name1_attribute1 Name1_attribute2 Name2_attribute1 Name2_attribute2
29/06/2020    11.04            97.30            19.67            94.28  
30/06/2020    11.05            97.38            19.68            94.31  
01/07/2020    11.06            97.46            19.61            93.95

我正在尝试获取以下字典结构(用于更多行和列):

{Name_1:{
    29/06/2020:{
    'Fixed String Attribute 1' : 11.04,
    'Second Fixed String Attribute 2' : 97.30},
    30/06/2020:{
    'Fixed String Attribute 1' : 11.05,
    'Second Fixed String Attribute 2' : 97.38},
    01/07/2020:{
    'Fixed String Attribute 1' : 11.06,
    'Second Fixed String Attribute 2' : 97.46}},
 {Name_2:{
    29/06/2020:{
    'Fixed String Attribute 1' : 19.67,
    'Second Fixed String Attribute 2' : 94.28},
    30/06/2020:{
    'Fixed String Attribute 1' : 19.68,
    'Second Fixed String Attribute 2' : 94.31},
    01/07/2020:{
    'Fixed String Attribute 1' : 19.61,
    'Second Fixed String Attribute 2' : 93.95}},  
  }

在查阅了 DataFrame.to_dict、Ordereddict 和 SO 的文档后,我找不到任何类似的问题。

非常感谢任何有关实现所需输出的建议!

【问题讨论】:

    标签: python python-3.x dictionary ordereddictionary


    【解决方案1】:

    你可以试试这样的:

    d = {}
    df.set_index('Date', inplace=True)
    data = df.T
    grp = data.groupby(data.index.str[:5])
    
    for i in grp.groups:
        d[i] = grp.get_group(i).to_dict()
    

    d:

    {'Name1': {'29/06/2020': {'Name1_attribute1': 11.04, 'Name1_attribute2': 97.3},
      '30/06/2020': {'Name1_attribute1': 11.05, 'Name1_attribute2': 97.38},
      '01/07/2020': {'Name1_attribute1': 11.06, 'Name1_attribute2': 97.46}},
     'Name2': {'29/06/2020': {'Name2_attribute1': 19.67,
       'Name2_attribute2': 94.28},
      '30/06/2020': {'Name2_attribute1': 19.68, 'Name2_attribute2': 94.31},
      '01/07/2020': {'Name2_attribute1': 19.61, 'Name2_attribute2': 93.95}}}
    

    然后重命名它们。

    【讨论】:

    • 谢谢,这解决了问题!我会投票,但没有足够的声誉。
    • 如果它解决了您的问题,然后通过单击勾选选项将其标记为解决方案。
    【解决方案2】:

    您可以尝试将宽格式转换为长格式,并将您想要的列索引为 dict 中的键。

    【讨论】:

      猜你喜欢
      • 2022-12-22
      • 2021-07-10
      • 2018-02-02
      • 2015-11-26
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      • 2018-05-04
      • 2020-05-24
      相关资源
      最近更新 更多