我使用pandas.io.data从肯·弗伦奇的数据库中获得了法马-法语因子,但是我不知道如何将整型的年-月日期索引(例如,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)发布于 2012-10-17 13:48:08
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个条目。
发布于 2013-06-03 16:29:09
尝试这个列表理解,它对我很有效:
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]https://stackoverflow.com/questions/12926660
复制相似问题