Python 将dataframe转换为与groupby嵌套的2级JSON
我有一个小要求,我需要以JSON格式列出给定两周内的所有客户及其金额-Python 将dataframe转换为与groupby嵌套的2级JSON,python,json,list,dictionary,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 CustomerSale
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}
]
}
]
我试着从一个角度来理解这个逻辑-
但我仍然停留在另一个层次
我也尝试过其他的方法,但没有成功。欢迎任何帮助。提前谢谢 您可以使用
CustomerSales
字典,其中键等于FortNight
值,而不是在每个字典中使用“FortNight”字符串作为键的字典列表,从而简化此操作。鉴于规定的要求,以下各项应适用。您可以循环遍历数据帧并构建字典。然后,第二组代码将该字典转换为您指定的格式
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"]
})
什么方法对你不起作用?目前我可以得到如下输出-[{'Customersales':[{'FortNight':'Apr-2FN-2018','Details':[{'Customer':'1100','Amount':198218.02}]}],{'Customersales':[{'FortNight':'Apr-3FN-2018','Details':[{'Customer':'1100','Amount:198218.02}]}],{'Customersales':[{'FortNight':'May-1FN-2018','Details':[{'Customer':'1100','Amount':198218.02}]}]