将 Pandas 的索引从整数格式更改为日期时间格式

5

我有一个非常大的数据框,其中包含日期时间表示形式的整数索引,例如20171001。我的任务是将其转换为日期时间格式,例如'2017-10-01'

为了简单起见,我生成了这样一个数据框。

>>> df = pd.DataFrame(np.random.randn(3,2), columns=list('ab'), index=
[20171001,20171002,20171003])
>>> df
             a         b
20171001  2.205108  0.926963
20171002  1.104884 -0.445450
20171003  0.621504 -0.584352
>>> df.index
Int64Index([20171001, 20171002, 20171003], dtype='int64')

如果我们将'to_datetime'应用于df.index,我们会得到奇怪的结果:

>>> pd.to_datetime(df.index)
DatetimeIndex(['1970-01-01 00:00:00.020171001',
           '1970-01-01 00:00:00.020171002',
           '1970-01-01 00:00:00.020171003'],
          dtype='datetime64[ns]', freq=None)

我想要的是 DatetimeIndex(['2017-10-01', '2017-10-02', '2017-10--3'], ...)。我该如何解决这个问题?请注意,文件已经给定。

2个回答

10

pd.to_datetime中使用format %Y%m%d, 例如:

pd.to_datetime(df.index, format='%Y%m%d')
DatetimeIndex(['2017-10-01', '2017-10-02', '2017-10-03'], dtype='datetime64[ns]', freq=None)

df.index = pd.to_datetime(df.index, format='%Y%m%d') 分配给索引。


1
谢谢Bharath,它有效。格式似乎意味着输入数据。完美。 - gnoejh

1

pd.to_datetime 是使用Pandas的方式。但是这里有两个替代方案:

import datetime
df.index = (datetime.datetime.strptime(str(i),"%Y%m%d") for i in df.index)

或者

import datetime
df.index = df.index.map(lambda x: datetime.datetime.strptime(str(x),"%Y%m%d"))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接