使用2级嵌套数组将数据帧转换为JSON

时间:2018-07-12 11:40:38

标签: python json pandas dictionary

我对Python编程有点陌生。我有一个小要求,我需要以JSON格式列出给定两周内的所有客户及其金额。

目前,我有这样一种数据框:

home-vagrant-app.mount

期望的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 
  Apr-2FN-2018   24797.00     11000     CustomerSales
  Apr-2FN-2018   21093.00     10990     CustomerSales

我尝试过:

"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}
           ]
    }
]

它检索此:

dict(df.set_index('Parameter').groupby(level=0).apply(lambda  x : ast.literal_eval(x.to_json(orient = 'records', date_format = "iso"))))

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

1 个答案:

答案 0 :(得分:1)

首先在参数 FortNight列上进行分组,然后在生成的分组行上使用.to_dict()以产生最里面的字典:

details = df.groupby(['Parameter', 'FortNight']).apply(
    lambda r: r[['Customer', 'Amount']].to_dict(orient='records'))

这为您提供了一系列在ParameterFortNight上具有多个索引的序列,并且值都是正确格式的所有列表,每个条目都包含Customer和{ {1}}列。如果您需要转换值类型,请先对Amount数据框结果进行转换,然后再对其调用r[['Customer', 'Amount']]

然后可以将系列unstack放入数据框,从而为您提供嵌套的参数-> FortNight->详细信息结构;参数值变成列,每个列表由FortNight索引的客户/金额字典:

to_dict()

如果将其变成字典,您将获得一本最正确的字典:

nested = details.unstack('Parameter')

但是对于您的格式,您需要将每一列中的值转换为>>> pprint(grouped.unstack('Parameter').to_dict()) {'CustomerSales': {'Apr-2FN-2018': [{'Amount': 339632.0, 'Customer': '10992'}, {'Amount': 27282.0, 'Customer': '10994'}, {'Amount': 26353.0, 'Customer': '10995'}, {'Amount': 24797.0, 'Customer': '11000'}, {'Amount': 21093.0, 'Customer': '10990'}]}} 映射的列表,然后然后将整个结构转换为字典:

{'FortNight': indexvalue, 'Details': value}

这将为您提供最终输出:

output = nested.apply(lambda s: [
    {s.index.name: idx, 'Details': value}
    for idx, value in s.items()
]).to_dict('records')

如果您需要JSON文档,请使用>>> pprint(output) [{'CustomerSales': {'Details': [{'Amount': 339632.0, 'Customer': '10992'}, {'Amount': 27282.0, 'Customer': '10994'}, {'Amount': 26353.0, 'Customer': '10995'}, {'Amount': 24797.0, 'Customer': '11000'}, {'Amount': 21093.0, 'Customer': '10990'}], 'FortNight': 'Apr-2FN-2018'}}] 而不是.to_json(orient='records')

放在一起作为一个表达式:

.to_dict('records')
相关问题