将数据框转换为嵌套有groupby的2级数据

时间:2018-07-12 14:56:13

标签: python json list dictionary

我有一个小要求,我需要以JSON格式列出给定两周内的所有客户及其金额。当前,我有这种方式的数据框-

  FortNight       Amount      Customer     Parameter
  Apr-2FN-2018   339632.00    10992     CustomerSales
  Apr-2FN-2018   27282.00     10994     CustomerSales 
  Apr-2FN-2018   26353.00     10995     CustomerSales 
  May-1FN-2018   24797.00     11000     CustomerSales
  May-1FN-2018   21093.00     10990     CustomerSales
  May-2FN-2018   45679.0      10992     CustomerSales
  May-2FN-2018   45459.0      10995     CustomerSales
  May-2FN-2018   35885.0      10994     CustomerSales

期望的JSON-

"CustomerSales" : [                                                                
    {"FortNight" : "Apr-2FN-2018",                                                                                      
         "Details" :[
             {"Customer":  "10992","Amount" : 339632.00},                                                                                                                                
             {"Customer":  "10994","Amount" : 27282.00},
             {"Customer":  "10995","Amount" : 26353.00}
           ]
    },
    {"FortNight" : "May-1FN-2018",                                                                                      
         "Details" :[
             {"Customer":  "11000","Amount" : 24797.00},                                                                                                                                
             {"Customer":  "10990","Amount" : 21093.00}
           ]
    },
    {"FortNight" : "May-2FN-2018",                                                                                      
         "Details" :[
             {"Customer":  "10992","Amount" : 45679.00},                                                                                                                                
             {"Customer":  "10995","Amount" : 45459.00},
             {"Customer":  "10994","Amount" : 35885.00}
           ]
    }
]

我尝试了- Convert dataframe to JSON with 2 level nested array

但是我仍然停留在另一个层次上。

我也尝试了其他方法,但徒劳无功。欢迎任何帮助。在此先感谢!! ...

1 个答案:

答案 0 :(得分:0)

您可以通过使用CustomerSales字典(其中键等于FortNight值)来简化此操作,而不必在每个字典中使用“ FortNight”字符串作为键来包含字典列表。给定指定的要求,以下应该起作用。您可以遍历DataFrame并构建字典。然后,第二组代码将该字典转换为您指定的格式。

sales = {}

for idx, row in df.iterrows():
    fn = row["FortNight"]
    fn_sales = sales.get(fn)
    if fn_sales is None:
        sales[fn] = {
                "Details": []
                }
        fn_sales = sales.get(fn)

    fn_sales["Details"].append({
            "Customer": row["Customer"],
            "Amount": row["Amount"]
            }
    )

sales_obj = {"CustomerSales": []}

for fn, details in sales.items():
    sales_obj["CustomerSales"].append({
            "FortNite": fn,
            "Details": details["Details"]
            })