如何将不同年份的月度价格回报合并到一个数据帧中?

2024-04-19 01:54:13 发布

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

我得到了2013年至2019年的月收益数据框,我想将月收益合并成一个数据框,其中列名称为2013年至2019年,索引为1月至12月。因此,我得到了2014年至2019年的月度回报数据框架

我怎么做?谢谢

import pandas as pd
import numpy as np
import matplotlib.pyplot as ply
import quandl

start=pd.to_datetime('2012.01.01')
end=pd.datetime.now()       #pd.to_datetime('2019.07.20')

btc= quandl.get("BITFINEX/BTCUSD.4",start_date=start,end_date=end, authtoken="F51kbhqij4J1o73V5vXT")

btc["pct"]=btc["Last"]/btc["Last"].shift(1)-1

btc=btc.resample(rule='M').apply(lambda x: x[-1])

btc["month_pct"]=btc["Last"]/btc["Last"].shift(1)-1

btc["year"]=btc.index.year
btc["month"]=btc.index.month_name()

btc_month=btc

btc_2014=btc_month.loc[btc_month["year"]==2014]
btc_2015=btc_month.loc[btc_month["year"]==2015]
btc_2016=btc_month.loc[btc_month["year"]==2016]
btc_2017=btc_month.loc[btc_month["year"]==2017]
btc_2018=btc_month.loc[btc_month["year"]==2018]
btc_2019=btc_month.loc[btc_month["year"]==2019]

enter image description here

btc_2019输出如下: enter image description here


Tags: to数据importdatetimeas收益yearstart