我有兴趣获取每个月的平均每月值,并将每月平均值设置为每个月的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
这是一种实现方法:
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
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。