だから私は辞書の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キーを使用して両方のリストを 1 つのデータフレームに結合します。
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
次に、傾向列をdictとして作成します
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 自体で修正することをお勧めします。