如何使用datetime索引合并两个数据帧,以便将一个数据帧中的a值分配给整个时段,直到没有新数据给定为止?

2024-04-27 16:11:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从两个数据帧计算市盈率。第一种是股票的月度收盘价,而第二种是年度/季度业绩信息

Prices:
Date    
2013-01-31  36.69
2013-02-28  36.92
2013-03-28  40.78
2013-04-30  46.05
2013-05-31  42.69
2013-06-28  41.34
2013-07-31  45.48        

Performance:
Date    
2009-12-31  358525000
2010-12-31  331309000
2011-12-31  487359000
2012-12-31  488766000
2013-12-31  432859000
2014-12-31  492609000
2015-12-31  360810000
2016-12-31  735524000

我想要:

Date        Price  Earnings
2013-01-31  36.69  432859000
2013-02-28  36.92  432859000
2013-03-28  40.78  432859000
2013-04-30  46.05  432859000
...

因此,保持数据框的行号与Price数据框中相同,但将收益分配给相应的每月收盘价


Tags: 数据信息dateperformanceprice股票prices月度
2条回答

试试这个

import pandas as pd

我为您提供的数据创建了数据文件。不过,我得把它们做成同样的长度

价格.txt

Date,Prices
2009-12-31,36.69
2013-01-31,36.69
2013-02-28,36.92
2013-03-28,40.78
2013-04-30,46.05
2013-05-31,42.69
2013-06-28,41.34
2013-07-31,45.48  

执行.txt

Date,Performance
2009-12-31,358525000
2010-12-31,331309000
2011-12-31,487359000
2012-12-31,488766000
2013-12-31,432859000
2014-12-31,492609000
2015-12-31,360810000
2016-12-31,735524000

然后进口

price = pd.read_csv('prices.txt', header=0)
per = pd.read_csv('perform.txt', header=0)

然后将日期设置为以下各项的索引:

price.Date = pd.to_datetime(price['Date'],format='%Y-%m-%d')
per.Date = pd.to_datetime(per['Date'],format='%Y-%m-%d')

price.set_index('Date', inplace=True)
per.set_index('Date', inplace=True)

我不得不从每一个额外的'年',以便我可以合并它们正确

price['year']= price.index.year
per['year']= per.index.year

然后用所需的数据创建一个新的数据帧

new=pd.merge(price, per, on='year', how='inner')
new.index=price.index

这就产生了

         Prices  year  Performance
Date                                 
2009-12-31   36.69  2009    358525000
2013-01-31   36.69  2013    432859000
2013-02-28   36.92  2013    432859000
2013-03-28   40.78  2013    432859000
2013-04-30   46.05  2013    432859000
2013-05-31   42.69  2013    432859000
2013-06-28   41.34  2013    432859000
2013-07-31   45.48  2013    432859000

在示例“性能”表中,日期是每年一次。如果您没有季度数据,您可以:

  1. 从两个表中提取年份

  2. 按年份执行左连接(例如pandas mergehttps://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html

当然,如果还有季度数据,那么在合并数据帧之前需要做一些技巧和调整

相关问题 更多 >