【问题标题】:Turning a Dataframe into a nested dictionary将 Dataframe 变成嵌套字典
【发布时间】:2021-12-30 12:25:07
【问题描述】:

我有一个如下所示的数据框。如何将其放入嵌套字典中,例如

     Guest  GuestCode          ProductName  Quantity Invoice No
0    Maria        NaN       Pro Plus Cream         2  OBFL22511
1    Maria        NaN  Soothe Stress Cream         1  OBFL22511
2  Sanchez  OBFLG3108       Pro Plus Cream         1  OBFL22524
3    Karen  OBFLG1600  Soothe Stress Cream         1  OBFL22525
4    Karen  OBFLG1600       Pro Plus Cream         1  OBFL22525

我希望将数据框转换为以下字典格式:

{"Guest": {"GuestCode": {"Invoice No": {"ProductName": Quantity}}}

例如:

{"Karen": {"OBFLG160": {"OBFL22525": {"Soothe Stress Cream": 1, "Pro Plus Cream": 1}}}

我试过了:

for index, row in df.iterrows():
    my_dict[row['Guest']] = {row['GuestCode']: {row['Invoice No']: {row['ProductName']}}}

但如果客人有多个产品,它不会列出所有项目。

我也尝试过并玩过这个,但不太了解字典理解:

d = {k: v.groupby('GuestCode')['Invoice No','ProductName' , 'Quantity'].apply(list).to_dict() for k, v in df.groupby('Guest')}

【问题讨论】:

    标签: python pandas dictionary for-loop nested


    【解决方案1】:
    my_dict = {k[0]: {k[1]: {k[2]: {p: q for p, q in row[['ProductName', 'Quantity']].values}}} for k, row in df.fillna('<NA>').groupby(['Guest', 'GuestCode', 'Invoice No'])}
    

    输出:

    >>> my_dict
    {'Karen': {'OBFLG1600': {'OBFL22525': {'Soothe Stress Cream': 1, 'Pro Plus Cream': 1}}},
     'Maria': {'<NA>': {'OBFL22511': {'Pro Plus Cream': 2, 'Soothe Stress Cream': 1}}},
     'Sanchez': {'OBFLG3108': {'OBFL22524': {'Pro Plus Cream': 1}}}}
    
    >>> import json
    >>> print(json.dumps(my_dict, indent=2))
    {
      "Karen": {
        "OBFLG1600": {
          "OBFL22525": {
            "Soothe Stress Cream": 1,
            "Pro Plus Cream": 1
          }
        }
      },
      "Maria": {
        "<NA>": {
          "OBFL22511": {
            "Pro Plus Cream": 2,
            "Soothe Stress Cream": 1
          }
        }
      },
      "Sanchez": {
        "OBFLG3108": {
          "OBFL22524": {
            "Pro Plus Cream": 1
          }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-01
      • 2019-07-24
      • 1970-01-01
      • 2013-11-16
      • 2019-04-08
      • 2019-06-27
      • 1970-01-01
      相关资源
      最近更新 更多