我有一个数据框df
,其索引结构如下所示:
>> df.index.values
array(['2017-12-19T07:00:04.753422000', '2017-12-19T07:00:09.628389000',
'2017-12-19T07:00:12.065880000', ...,
'2018-01-22T15:29:52.462586000', '2018-01-22T15:29:54.900103000',
'2018-01-22T15:29:56.728234000'], dtype='datetime64[ns]')
正如您所看到的,dtype
索引为datetime64[ns]
。 如何将dtype
更新为datetime64[us]
? (this post对我不起作用)。
确实主要问题来自于调用此函数df.to_sql('table_name', engine)
将df
插入postgre中的表中。我收到了以下错误:
错误:无法将DatetimeIndex强制转换为dtype datetime64 [us]
答案 0 :(得分:0)
您可以单独转换DatetimeIndex
,如果将pandas分配回来并转换为默认ns
:
idx = pd.DatetimeIndex(['2017-12-19T07:00:04.753422000', '2017-12-19T07:00:09.628389000',
'2017-12-19T07:00:12.065880000',
'2018-01-22T15:29:52.462586000', '2018-01-22T15:29:54.900103000',
'2018-01-22T15:29:56.728234000'])
df = pd.DataFrame({'a':range(6)}, index=idx)
print (df)
a
2017-12-19 07:00:04.753422 0
2017-12-19 07:00:09.628389 1
2017-12-19 07:00:12.065880 2
2018-01-22 15:29:52.462586 3
2018-01-22 15:29:54.900103 4
2018-01-22 15:29:56.728234 5
idx = df.index.values.astype('datetime64[us]')
print (idx.dtype)
datetime64[us]
df.index = df.index.values.astype('datetime64[us]')
print (df.index.dtype)
datetime64[ns]
如果使用其他值 - 例如到ms
,然后地板看起来更好:
df.index = df.index.values.astype('datetime64[ms]')
print (df)
a
2017-12-19 07:00:04.753 0
2017-12-19 07:00:09.628 1
2017-12-19 07:00:12.065 2
2018-01-22 15:29:52.462 3
2018-01-22 15:29:54.900 4
2018-01-22 15:29:56.728 5