I am a bit new to Python programming. I have a small requirement where in I need to list down all customers and their amounts for a given fortnight in a JSON format.
Currently, I have a dataframe this way:
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
Apr-2FN-2018 24797.00 11000 CustomerSales
Apr-2FN-2018 21093.00 10990 CustomerSales
Expected JSON:
"CustomerSales" : [
{"FortNight" : "Apr-2FN-2018",
"Details" :[
{"Customer": "10992","Amount" : 339632.00},
{"Customer": "10994","Amount" : 27282.00},
{"Customer": "10995","Amount" : 26353.00},
{"Customer": "11000","Amount" : 24797.00},
{"Customer": "10990","Amount" : 21093.00}
]
}
]
I tried:
dict(df.set_index('Parameter').groupby(level=0).apply(lambda x : ast.literal_eval(x.to_json(orient = 'records', date_format = "iso"))))
It retrieves this:
[{'CustomerSales':
[{'Customer': '10992', 'Amount': 339632.00, 'FortNight': 'Apr-2FN-2018'}, {'Customer': '10994', 'Amount': 27282.00, 'FortNight': 'Apr-2FN-2018'},{'Customer': '10995', 'Amount': 26353.00, 'FortNight': 'Apr-2FN-2018'},
{'Customer': '11000', 'Amount': 24797.00, 'FortNight': 'Apr-2FN-2018'},
{'Customer': '10990', 'Amount': 21093.00, 'FortNight': 'Apr-2FN-2018'}]}]
I tried other ways too but in vain. Any help is welcome. Thanks in advance!