【问题标题】:Convert integer index from Fama-French factors to datetime index in pandas将整数索引从 Fama-French 因子转换为 pandas 中的日期时间索引
【发布时间】:2012-10-07 06:12:54
【问题描述】:

我使用 pandas.io.data 从 Ken French 的数据库中获取 Fama-French 因子,但我不知道如何将整数年月日期索引(例如,200105)转换为 datetime 索引以便我可以利用更多pandas 功能。

以下代码运行,但我在最后一个未注释行中的索引尝试删除了 DataFrame ff 中的所有数据。我也试过.reindex(),但这不会将索引更改为rangepandas 方式是什么?谢谢!

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)

【问题讨论】:

    标签: python datetime pandas


    【解决方案1】:

    试试这个列表推导,它对我有用:

    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]
    

    【讨论】:

    • 每日数据会是什么样子?我必须在 ff.index = [dt.datetime(d/100, d%100, XYZ) for d in ff.index] 中的 XYZ 中添加什么?
    【解决方案2】:

    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
    

    这有点慢,所以如果您有很多观察结果,您可能希望在 pandas 中使用优化 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 个条目。

    【讨论】:

    • 谢谢!考虑到我使用.columns,应该很明显。
    • 但是有没有办法将整数索引转换为字符串然后使用日期解析器?或者我应该编写一个包装器来从两个端点进行这个日期转换?
    • 谢谢! “列表中的循环”是我在列表中使用 str() 时缺少的习语。谢谢。
    猜你喜欢
    • 2018-10-30
    • 2020-01-16
    • 2017-06-17
    • 2016-10-05
    • 2017-07-11
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多