Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将索引从整数格式更改为日期时间格式_Python_Pandas_Datetime - Fatal编程技术网

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

Python 将索引从整数格式更改为日期时间格式,python,pandas,datetime,Python,Pandas,Datetime,我有一个巨大的数据框,其中包含用于日期时间表示的整数形式的索引,例如,20171001。我要做的是将表单(例如,20171001)更改为日期时间格式,'2017-10-01' 为了简单起见,我生成了这样一个数据帧 >>> df = pd.DataFrame(np.random.randn(3,2), columns=list('ab'), index= [20171001,20171002,20171003]) >>> df a

我有一个巨大的数据框,其中包含用于日期时间表示的整数形式的索引,例如,
20171001
。我要做的是将表单(例如,
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']、…)

我如何处理这个问题?请注意,文件是给定的。

pd.to\u datetime
中使用
格式%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,格式=“%Y%m%d”)
pd.To_datetime就是这样做的。但这里有两种选择:

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"))