我使用 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
将现有索引重新对齐到给定索引,而不是更改索引。
如果您已确保长度和对齐匹配,您可以只执行 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 个条目。
关于python - 将整数索引从 Fama-French 因子转换为 Pandas 中的日期时间索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12926660/