所以我有2个字典列表..
list_yearly = [
{'name':'john',
'total_year': 107
},
{'name':'cathy',
'total_year':124
},
]
list_monthly = [
{'name':'john',
'month':'Jan',
'total_month': 34
},
{'name':'cathy',
'month':'Jan',
'total_month':78
},
{'name':'john',
'month':'Feb',
'total_month': 73
},
{'name':'cathy',
'month':'Feb',
'total_month':46
},
]
目标是获得如下所示的最终数据集:
{'name':'john',
'total_year': 107,
'trend':[{'month':'Jan', 'total_month': 34},{'month':'Feb', 'total_month': 73}]
},
{'name':'cathy',
'total_year':124,
'trend':[{'month':'Jan', 'total_month': 78},{'month':'Feb', 'total_month': 46}]
},
由于我的数据集适用于特定年份所有 12 个月的大量学生,因此我使用 Pandas 进行数据处理。这就是我的做法:
首先使用name键将两个列表组合成一个数据框。
In [5]: df = pd.DataFrame(list_yearly).merge(pd.DataFrame(list_monthly))
In [6]: df
Out[6]:
name total_year month total_month
0 john 107 Jan 34
1 john 107 Feb 73
2 cathy 124 Jan 78
3 cathy 124 Feb 46
然后创建一个趋势列作为字典
ln [7]: df['trend'] = df.apply(lambda x: [x[['month', 'total_month']].to_dict()], axis=1)
In [8]: df
Out[8]:
name total_year month total_month \
0 john 107 Jan 34
1 john 107 Feb 73
2 cathy 124 Jan 78
3 cathy 124 Feb 46
trend
0 [{u'total_month': 34, u'month': u'Jan'}]
1 [{u'total_month': 73, u'month': u'Feb'}]
2 [{u'total_month': 78, u'month': u'Jan'}]
3 [{u'total_month': 46, u'month': u'Feb'}]
并且,使用to_dict(orient='records')
选定列的方法将其转换回字典列表:
In [9]: df[['name', 'total_year', 'trend']].to_dict(orient='records')
Out[9]:
[{'name': 'john',
'total_year': 107,
'trend': [{'month': 'Jan', 'total_month': 34}]},
{'name': 'john',
'total_year': 107,
'trend': [{'month': 'Feb', 'total_month': 73}]},
{'name': 'cathy',
'total_year': 124,
'trend': [{'month': 'Jan', 'total_month': 78}]},
{'name': 'cathy',
'total_year': 124,
'trend': [{'month': 'Feb', 'total_month': 46}]}]
很明显,最终的数据集并不是我想要的。而不是包含两个月份的 2 个字典,而是得到 4 个将所有月份分开的字典。我该如何解决这个问题?我宁愿在 Pandas 本身中修复它,而不是使用这个最终输出再次将其减少到所需状态