如何填充时间序列数据框直到月底
how to fill a time series dataframe until end of month
我有一个数据框,其中索引是一个日期(每天,跳过周末)。这些数据是从 API 下载的,用于进一步的财务分析,但是 analysis/code 仅在日期索引中的最后一天是月末时运行,否则我希望代码找到月末月并使用每列的最后一个可用值填充从今天到月末日期的数据框。
所以我有:
Date Value
... ...
2020-06-23 7
2020-06-24 7.1
2020-06-25 7
2020-06-26 7.3 (assume today)
我想要的是:
Date Value
... ...
2020-06-23 7
2020-06-24 7.1
2020-06-25 7
2020-06-26 7.3
2020-06-29 7.3
2020-06-30 7.3
跳过周末。谢谢。路易吉
使用DataFrame.reindex
by maximum datetime converted to end of month date and then remove weekends by boolean indexing
with DatetimeIndex.weekday
:
df['Date'] = pd.to_datetime(df['Date'])
df = df.set_index('Date')
idx = pd.date_range(df.index.min(), df.index.max().to_period('M').to_timestamp('M'))
df = df.reindex(idx, method='ffill')
df = df[df.index.weekday < 5]
print (df)
Value
2020-06-23 7.0
2020-06-24 7.1
2020-06-25 7.0
2020-06-26 7.3
2020-06-29 7.3
2020-06-30 7.3
我有一个数据框,其中索引是一个日期(每天,跳过周末)。这些数据是从 API 下载的,用于进一步的财务分析,但是 analysis/code 仅在日期索引中的最后一天是月末时运行,否则我希望代码找到月末月并使用每列的最后一个可用值填充从今天到月末日期的数据框。
所以我有:
Date Value
... ...
2020-06-23 7
2020-06-24 7.1
2020-06-25 7
2020-06-26 7.3 (assume today)
我想要的是:
Date Value
... ...
2020-06-23 7
2020-06-24 7.1
2020-06-25 7
2020-06-26 7.3
2020-06-29 7.3
2020-06-30 7.3
跳过周末。谢谢。路易吉
使用DataFrame.reindex
by maximum datetime converted to end of month date and then remove weekends by boolean indexing
with DatetimeIndex.weekday
:
df['Date'] = pd.to_datetime(df['Date'])
df = df.set_index('Date')
idx = pd.date_range(df.index.min(), df.index.max().to_period('M').to_timestamp('M'))
df = df.reindex(idx, method='ffill')
df = df[df.index.weekday < 5]
print (df)
Value
2020-06-23 7.0
2020-06-24 7.1
2020-06-25 7.0
2020-06-26 7.3
2020-06-29 7.3
2020-06-30 7.3