使用自定义的解析功能将索引转换为大熊猫中的日期时间

发痒的

我正在使用内置的pandas DataReader从Fama-French数据库中下载数据。日期最初只是整数,其yyyymm格式为:

import pandas.io.data as web
ff = web.DataReader("F-F_Research_Data_Factors", "famafrench")[0]
ff.head()

在此处输入图片说明

我想将索引转换为日期时间,其中日期是该月的最后一天。现在,我正在这样做:

ff.reset_index(inplace=True)

import calendar
def dateParser(dt):
    yyyy = int(dt[0:4])
    mm = int(dt[4:6])
    dd = calendar.monthrange(yyyy,mm)[1]   #last day of month
    return pd.datetime(yyyy,mm,dd)

ff['date'] = ff['index'].astype(str).apply(dateParser)
ff.index = ff['date']

ff.drop(['index', 'date'], axis=1, inplace=True)

有没有更快/更优雅的方式来实现这一目标?例如,有没有一种方法可以dateParser直接应用到索引(也许是就位),所以我不必reset_index首先应用?

杰夫
In [35]: ff = web.DataReader("F-F_Research_Data_Factors", "famafrench")[0]

In [36]: ff.head()
Out[36]: 
        1 Mkt-RF  2 SMB  3 HML  4 RF
192607      2.96  -2.30  -2.87  0.22
192608      2.64  -1.40   4.19  0.25
192609      0.36  -1.32   0.01  0.23
192610     -3.24   0.04   0.51  0.32
192611      2.53  -0.20  -0.35  0.31

In [38]: ff.index
Out[38]: 
Int64Index([192607, 192608, 192609, 192610, 192611, 192612, 192701, 192702, 192703, 192704, 
            ...
            201407, 201408, 201409, 201410, 201411, 201412, 201501, 201502, 201503, 201504],
           dtype='int64', length=1066)

In [39]: ff.index = pd.to_datetime(ff.index,format='%Y%m') + pd.offsets.MonthEnd()

In [40]: ff.index
Out[40]: 
DatetimeIndex(['1926-07-31', '1926-08-31', '1926-09-30', '1926-10-31', '1926-11-30', '1926-12-31', '1927-01-31', '1927-02-28', '1927-03-31', '1927-04-30', 
               ...
               '2014-07-31', '2014-08-31', '2014-09-30', '2014-10-31', '2014-11-30', '2014-12-31', '2015-01-31', '2015-02-28', '2015-03-31', '2015-04-30'],
              dtype='datetime64[ns]', length=1066, freq='M', tz=None)

In [41]: ff.head()
Out[41]: 
            1 Mkt-RF  2 SMB  3 HML  4 RF
1926-07-31      2.96  -2.30  -2.87  0.22
1926-08-31      2.64  -1.40   4.19  0.25
1926-09-30      0.36  -1.32   0.01  0.23
1926-10-31     -3.24   0.04   0.51  0.32
1926-11-30      2.53  -0.20  -0.35  0.31

请注意,实际上转换索引的速度更快,如下所示,因为格式具有快速路径。

pd.to_datetime(ff.index*100+1,format='%Y%m%d') + pd.offsets.MonthEnd()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何自定义大熊猫解析日期

将大熊猫(多)索引解析为日期时间

大熊猫中是否具有将CST转换为时区的时间戳的功能?

大熊猫DataFrame中的自定义浮动格式

是否可以将大熊猫的日期时间转换为工作日/周末和季节?

大熊猫:从read_sql导入后,将列解析/转换为日期

带有大熊猫日期时间索引的列表理解

如何转换到熊猫日期时间到大熊猫中的整数?

大熊猫将索引值转换为小写

将索引转换为大熊猫以作图

转换成大熊猫的日期时间格式?

将大熊猫日期转换为星期数

CSV文件打开时,大熊猫中的日期时间转换错误

如何将以YYYYMMDD存储的日期转换为大熊猫中的datetime格式

如何不将date_string转换为大熊猫中的日期?

具有自定义值权重的大熊猫中的虚拟编码

大熊猫:使用基于不同DF的自定义列创建DF

如何将字符串日期(2020年11月13日)转换为大熊猫中的日期时间?

按日期,自定义聚合器对大熊猫进行排序:合并每个日期的所有数据

如何根据日期来过滤大熊猫中的时间?

将自定义/自定义日期时间格式转换为日期时间 SQL Server

将日期时间转换为自定义格式

将时间戳转换为熊猫中的自定义时段之一

将熊猫中的日期时间索引转换为单独的列

如何将熊猫中的索引转换为日期时间?

将系列转换为大熊猫

将熊猫索引转换为日期时间

使用大熊猫,索引错误

如何将大熊猫的字符串时间转换为纳秒时间