我想将肯尼思·法文(Kenneth French)网站上的日期与以下代码集成在一起,该代码可以很好地处理月度数据。但是由于我现在需要每日数据,因此我需要知道为变量XYZ(在代码的最后一行中)要放置什么才能使其工作:
import pandas.io.data
import pandas as pd
from datetime import datetime, date
io = pandas.io.data.DataReader("F-F_Research_Data_Factors_daily", "famafrench")
ff = io[0] # Bestimmung des Dictionary Teils aus der FF Zip Datei
ff.columns = ['Mkt_rf', 'SMB', 'HML', 'rf']
ff.index = [datetime(d/100, d%100, XYZ) for d in ff.index]
索引如下所示:
Int64Index([19260701, 19260702, 19260706, 19260707, 19260708, 19260709, 19260710, 19260712, 19260713, 19260714, 19260715, 19260716, 19260717, 19260719, 19260720, 19260721, 19260722, 19260723, 19260724, 19260726, 19260727, 19260728, 19260729, 19260730, 19260731, 19260802, 19260803, 19260804, 19260805, 19260806, 19260807, 19260809, 19260810, 19260811, 19260812, 19260813, 19260814, 19260816, 19260817, 19260818, 19260819, 19260820, 19260821, 19260823, 19260824, 19260825, 19260826, 19260827, 19260828, 19260830, 19260831, 19260901, 19260902, 19260903, 19260907, 19260908, 19260909, 19260910, 19260911, 19260913, 19260914, 19260915, 19260916, 19260917, 19260918, 19260920, 19260921, 19260922, 19260923, 19260924, 19260925, 19260927, 19260928, 19260929, 19260930, 19261001, 19261002, 19261004, 19261005, 19261006, 19261007, 19261008, 19261009, 19261011, 19261013, 19261014, 19261015, 19261016, 19261018, 19261019, 19261020, 19261021, 19261022, 19261023, 19261025, 19261026, 19261027, 19261028, 19261029, 19261030, ...], dtype='int64')
数据框如下所示:
Mkt_rf SMB HML rf
19260701 0.10 -0.24 -0.28 0.009 # the integer 19260701 needs to get converted to a datetime copartible format such as 1926/07/01
... ... ... ... ...
20150430 -1.11 -1.04 0.73 0.000
[23467 rows x 4 columns]
我用熊猫0.16.1
有任何想法吗?
最佳答案
要将索引转换为DatetimeIndex,可以使用to_datetime
:
ff.index = pd.to_datetime(ff.index, format='%Y%m%d')
当日期为整数时,通过指定
format='%Y%m%d'
和to_datetime
可以完成上述操作,并将整数视为该格式的字符串。一个小例子:In [2]: pd.to_datetime([19260701, 19260702], format='%Y%m%d')
Out[2]: DatetimeIndex(['1926-07-01', '1926-07-02'], dtype='datetime64[ns]', freq=None, tz=None)