我正在开发Web API,我从查询结果中得到了一个列表,如下所示:
[{'ORG': 'Asset Management',
'SURVEY_DATE': datetime.date(2018, 4, 23),
'NOS': '1'},
{'ORG': 'Asset Management',
'SURVEY_DATE': datetime.date(2018, 5, 8),
'NOS': '1'},
{'ORG': 'Chief Advocacy Office',
'SURVEY_DATE': datetime.date(2018, 10, 31),
'NOS': '50'},
{'ORG': 'Chief Advocacy Office',
'SURVEY_DATE': datetime.date(2019, 2, 13),
'NOS': '1'},
{'ORG': 'Chief Information Office',
'SURVEY_DATE': datetime.date(2018, 1, 22),
'NOS': '1'},
{'ORG': 'Chief Information Office',
'SURVEY_DATE': datetime.date(2018, 2, 2),
'NOS': '1'}]
我试图先将其转换为数据框并像这样进行编码:
df1 = df1.groupby('ORG').apply(lambda x: dict(zip(x['SURVEY_DATE'],x['NOS']))).to_dict()
但是有没有一种方法不需要在数据框中转换它?
我想将其格式化为以下字典中的响应数据字典:
{
"Asset Management": [
{
"date": "2019-03-30",
"numberOfSurveys": 76
},
{
"date": "2019-03-31",
"numberOfSurveys": 83
}
],
"Chief Advocacy Office": [
{
"date": "2019-03-30",
"numberOfSurveys": 50
},
{
"date": "2019-03-31",
"numberOfSurveys": 40
}
],
"Chief Information Office": [
{
"date": "2019-03-30",
"numberOfSurveys": 50
},
{
"date": "2019-03-31",
"numberOfSurveys": 40
}
]
}
答案 0 :(得分:4)
import collections
result = collections.defaultdict(list)
for row in original_data:
result[row['ORG']].append({
'date': row['SURVEY_DATE'],
'numberOfSurveys': row['NOS'],
})