我有一个这样的字典列表:
[
{'2016-06-11': 10,
'2016-06-09': 10,
'ID': 1,
'2016-06-04': 10,
'2016-06-07': 10,
'2016-06-06': 10,
'2016-06-01': 10,
'2016-06-03': 10,
'type': 'primary',
'2016-06-05': 10,
'2016-06-10': 10,
'2016-06-02': 10,
'2016-06-08': 10},
{'2016-06-11': 2,
'2016-06-09': 1,
'ID': 2,
'type': 'secondary',
'2016-06-04': 1,
'2016-06-07': 1,
'2016-06-06': 1,
'2016-06-01': 1,
'2016-06-03': 1,
'2016-06-05': 1,
'2016-06-10': 2,
'2016-06-02': 1,
'2016-06-08': 1}
]
我需要将其转换为类似的字典列表,其中键为周(从星期一开始,例如 2016-06-03 - 2016-06-09
)或月(例如 2016-06
),这些值将是该周/月值的平均值或中值。执行此操作的最简单方法是什么?
最佳答案
我想你可以resample
按月
,汇总mean
或 median
最后通过 DataFrame.to_dict
创建 dict
的 list
:
df = pd.DataFrame(d)
print (df)
2016-06-01 2016-06-02 2016-06-03 2016-06-04 2016-06-05 2016-06-06 \
0 10 10 10 10 10 10
1 1 1 1 1 1 1
2016-06-07 2016-06-08 2016-06-09 2016-06-10 2016-06-11 ID type
0 10 10 10 10 10 1 primary
1 1 1 1 2 2 2 secondary
df.set_index(['type', 'ID'], inplace=True)
df.columns = pd.to_datetime(df.columns)
df = df.T.resample('M').mean()
df.index = df.index.strftime('%Y-%m')
print (df)
type primary secondary
ID 1 2
2016-06 10.0 1.181818
print (df.T.reset_index().to_dict(orient='records'))
[{'type': 'primary', '2016-06': 10.0, 'ID': 1},
{'type': 'secondary', '2016-06': 1.1818181818181819, 'ID': 2}]
df.set_index(['type', 'ID'], inplace=True)
df.columns = pd.to_datetime(df.columns)
df = df.T.resample('M').median()
df.index = df.index.strftime('%Y-%m')
print (df)
type primary secondary
ID 1 2
2016-06 10 1
print (df.T.reset_index().to_dict(orient='records'))
[{'type': 'primary', '2016-06': 10, 'ID': 1},
{'type': 'secondary', '2016-06': 1, 'ID': 2}]
另一种解决方案 reample
是 groupby
按 DatetimeIndex.to_period
创建的月份:
df = df.groupby([df.index.to_period('m')]).mean()
df = df.groupby([df.index.to_period('m')]).median()
关于python - 将每日数据转换为每周均值和中位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40014986/