python - Pandas 数据读取器 : normalizing dates

标签 python pandas pandas-datareader

我使用 pandas 数据读取器包从 Fred、雅虎财经等网站提取经济时间序列。我从“fred”网站中提取了美国经济衰退 (USREC) 系列,并从雅虎财经中提取了历史 sp500 (^GSPC)。

美国历史性衰退:

web.DataReader("USREC", "fred", start, end)

输出:

2017-08-01      0
2017-09-01      0
2017-10-01      0
2017-11-01      0

标准普尔 500 指数返回

web.DataReader("^GSPC",'yahoo',start,end)['Close'].to_frame().resample('M').mean().round()

输出:

2017-08-31  2456.0
2017-09-30  2493.0
2017-10-31  2557.0
2017-11-30  2594.0

我想合并两个数据框,但一个具有该月的开始日期,另一个具有该月的结束日期。如何制作 a) 日期列 yyyy-mm b) 使两个框架的日期列为月开始或月结束?

感谢您的帮助!

最佳答案

您可以在月初使用 MS 重新采样:

web.DataReader("^GSPC",'yahoo',start,end)['Close'].to_frame().resample('MS').mean().round()

或者可以使用 to_period 表示月份PeriodIndex:

df1 = df1.to_period('M')
df2 = df2.to_period('M')
print (df1)
         Close
2017-08      0
2017-09      0
2017-10      0
2017-11      0

print (df2)
          Close
2017-08  2456.0
2017-09  2493.0
2017-10  2557.0
2017-11  2594.0

print (df1.index)
PeriodIndex(['2017-08', '2017-09', '2017-10', '2017-11'], dtype='period[M]', freq='M')

print (df2.index)
PeriodIndex(['2017-08', '2017-09', '2017-10', '2017-11'], dtype='period[M]', freq='M')

关于python - Pandas 数据读取器 : normalizing dates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47952901/

相关文章:

python - 为 View web2py 内的表字段设置默认值

python-3.x - 如何绘制连接条形图顶部的线

python - 使用 usecols 时 pandas.read_excel 错误

Python pandas datareader 不再适用于 yahoo-finance 更改的 url

python - 在 python 中运行 cmd

python - 递归地反转字符串?

创建集合的 Python 性能比较 - set() 与 {} 文字

python - Pandas:在一个箱线图中为传单设置不同的颜色

python - Pandas : dropping multiple columns and keeping only ones with numeric data

python - 确定 Pandas 的年度营业年度