我有兴趣获取每个月的月平均值,并将月平均值设置为每月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的每月价值?
编辑:
您的建议使用np.tile()很好,但是我最终需要对多列进行此操作。我使用的不是np.tile:
index = pd.date_range(start='1/1/1950', end='12/31/1999', freq='MS')
m_avg = pd.concat([month]*49,axis=0).set_index(index)
可能有更好的解决方案,但这到目前为止满足了我的需求。
答案 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