首先对两个参数进行分组andFortNight 列,并使用.to_dict()
在结果分组行上生成最里面的字典:
details = df.groupby(['Parameter', 'FortNight']).apply(
lambda r: r[['Customer', 'Amount']].to_dict(orient='records'))
这为您提供了一个具有多索引的系列Parameter
and FortNight
,并且值是正确格式的所有列表,每个条目都是一个字典Customer
and Amount
列。如果需要转换值类型,请在r[['Customer', 'Amount']]
调用前的数据帧结果to_dict()
on it.
那么你可以unstack将系列放入数据帧中,为您提供嵌套的参数 -> FortNight -> 详细信息结构;参数值成为列,每个客户/金额字典列表均由 FortNight 索引:
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}
映射,then将整个结构转换为字典:
output = nested.apply(lambda s: [
{s.index.name: idx, 'Details': value}
for idx, value in s.items()
]).to_dict('records')
这将为您提供最终输出:
>>> 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'}}]
如果您需要 JSON 文档,请使用.to_json(orient='records')
而不是.to_dict('records')
.
放在一起作为一个表达式:
df.groupby(['Parameter', 'FortNight']).apply(
lambda r: r[['Customer', 'Amount']].to_dict(orient='records')
).unstack('Parameter').apply(lambda s: [
{s.index.name: idx, 'Details': value}
for idx, value in s.items()]
).to_json(orient='records')