开发者社区> 问答> 正文

从每月平均数据帧到内插的每日时间序列

我有兴趣获取每个月的平均每月值,并将每月平均值设置为每个月的15日(在每日时间序列内)的值。

我从以下内容开始(这些是我得到的每月平均值):

m_avg = pd.DataFrame({'Month':['1.527013956','1.899169054','1.669356146','1.44920871','1.188557788','1.017035727','0.950243755','1.022453993','1.203913739',' 1.369545041','1.441827406','1.48621651']

编辑:我向数据框添加了一个更多的值,以便现在有12个值。

接下来,我想将每个月度值分别放在以下时间段的第15天(每个月内):

ts = pd.date_range(start='1/1/1950', end='12/31/1999', freq='D')

我知道如何通过使用以下命令在已经存在的每日时间序列的第15天提取日期:

df= df.loc[(df.index.day==15)] # Where df is any daily timeseries

最后,我知道如何在每个月的第15天获得月平均值后对值进行插值,方法是:

df.loc[:, ['Col1']] = df.loc[:, ['Col1']].interpolate(method='linear', limit_direction='both', limit=100)

我如何从每月DataFrame过渡到插值的每日DataFrame,在每个月的第15天之间线性插值,这是按构造计算的原始DataFrame的每月价值?

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 21:53:49 578 0
1 条回答
写回答
取消 提交回答
  • 这是一种实现方法:

    import pandas as pd
    import numpy as np
    
    # monthly averages, note these should be cast to float 
    month = np.array(['1.527013956', '1.899169054', '1.669356146', 
                      '1.44920871',  '1.188557788', '1.017035727',
                      '0.950243755', '1.022453993', '1.203913739', 
                      '1.369545041', '1.441827406', '1.48621651'], dtype='float')
    
    # expand this to 51 years, with the same monthly averages repeating each year
    # (obviously not very efficient, probably there are better ways to attack the problem, 
    # but this was the question)
    month = np.tile(month, 51)
    
    # create DataFrame with these values
    m_avg = pd.DataFrame({'Month': month})
    
    # set the date index to the desired time period
    m_avg.index = pd.date_range(start='1/1/1950', end='12/1/2000', freq='MS')
    
    # shift the index by 14 days to get the 15th of each month
    m_avg = m_avg.tshift(14, freq='D')
    
    # expand the index to daily frequency
    daily = m_avg.asfreq(freq='D')
    
    # interpolate (linearly) the missing values
    daily = daily.interpolate()
    
    # show result
    display(daily)
    

    输出:

                Month
    1950-01-15  1.527014
    1950-01-16  1.539019
    1950-01-17  1.551024
    1950-01-18  1.563029
    1950-01-19  1.575034
    ...         ...
    2000-12-11  1.480298
    2000-12-12  1.481778
    2000-12-13  1.483257
    2000-12-14  1.484737
    2000-12-15  1.486217
    
    18598 rows × 1 columns
    

    回答来源:stackoverflow

    2020-03-24 21:53:57
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载