Skip to main content
 首页 » 编程设计

python之Pandas 数据读取器 : normalizing dates

2024年09月07日17傻小

我使用 pandas 数据阅读器包从 fred、yahoo finance 等网站提取经济时间序列。我从“fred”网站和雅虎金融的历史 sp500 (^GSPC) 中提取了美国经济衰退 (USREC) 系列。

美国历史性经济衰退:

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')