【问题标题】:Converting daily data to weekly means and medians将每日数据转换为每周平均值和中位数
【发布时间】:2017-02-22 05:20:36
【问题描述】:

我有一个这样的字典列表:

[
    {'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),并且值可以是平均值或该周/月值的中位数。最简单的方法是什么?

【问题讨论】:

    标签: python date pandas mean median


    【解决方案1】:

    我认为你可以 resample by months,聚合 meanmedian 最后创建 list of dict by DataFrame.to_dict

    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}]
    

    另一个解决方案 reamplegroupby 按由 DatetimeIndex.to_period 创建的月份:

    df = df.groupby([df.index.to_period('m')]).mean()
    df = df.groupby([df.index.to_period('m')]).median()
    

    【讨论】:

    • 这是完美的。我想我现在可以自己计算出每周平均数了,非常感谢!
    • 很高兴能帮到你!
    猜你喜欢
    • 2018-01-24
    • 1970-01-01
    • 2018-02-15
    • 2015-05-11
    • 2020-07-06
    • 1970-01-01
    • 2019-12-20
    • 2020-06-13
    • 2016-01-29
    相关资源
    最近更新 更多