簡體   English   中英

將Fama-French因子中的整數索引轉換為熊貓中的日期時間索引

[英]Convert integer index from Fama-French factors to datetime index in pandas

我使用pandas.io.data從Ken French的數據庫中獲得了Fama-French因子,但是我不知道如何將整數年月日期索引(例如200105 )轉換為datetime索引,以便我可以更多pandas功能的優勢。

下面的代碼運行,但是我在未注釋的最后一行中的索引嘗試將刪除DataFrame ff所有數據。 我也嘗試過.reindex() ,但這不會將索引更改為range pandas是什么方式? 謝謝!

import pandas as pd
from pandas.io.data import DataReader
import datetime as dt

ff = pd.DataFrame(DataReader("F-F_Research_Data_Factors", "famafrench")[0])
ff.columns = ['Mkt_rf', 'SMB', 'HML', 'rf']

start = ff.index[0]
start = dt.datetime(year=start//100, month=start%100, day=1)
end = ff.index[-1]
end = dt.datetime(year=end//100, month=end%100, day=1)
range = pd.DateRange(start, end, offset=pd.datetools.MonthEnd())
ff = pd.DataFrame(ff, index=range)
#ff.reindex(range)

reindex將現有索引與給定reindex重新對齊,而不是更改索引。 如果您確定長度和對齊方式匹配,則只需執行ff.index = range

解析每個原始索引值要安全得多。 一種簡單的方法是通過轉換為字符串來做到這一點:

In [132]: ints
Out[132]: Int64Index([201201, 201201, 201201, ..., 203905, 203905, 203905])

In [133]: conv = lambda x: datetime.strptime(str(x), '%Y%m')

In [134]: dates = [conv(x) for x in ints]

In [135]: %timeit [conv(x) for x in ints]
1 loops, best of 3: 222 ms per loop

這有點慢,因此,如果您有很多觀察,則可能要在熊貓中使用優化cython函數:

In [144]: years = (ints // 100).astype(object)

In [145]: months = (ints % 100).astype(object)

In [146]: days = np.ones(len(years), dtype=object)

In [147]: import pandas.lib as lib

In [148]: %timeit Index(lib.try_parse_year_month_day(years, months, days))
100 loops, best of 3: 5.47 ms per loop

在這里, ints具有10000個條目。

試試這個列表理解,它對我有用:

ff = pd.DataFrame(DataReader("F-F_Research_Data_Factors", "famafrench")[0])
ff.columns = ['Mkt_rf', 'SMB', 'HML', 'rf']    
ff.index = [dt.datetime(d/100, d%100, 1) for d in ff.index]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM