Convert datetime64[ns] column to DatetimeIndex in pandas

杀马特。学长 韩版系。学妹 提交于 2021-01-28 14:24:05

问题


One of the packages that I am working with has a pre-requisite that the index of the data frame needs to be a pandas DatetimeIndex. So, I have been trying to convert a column of the data type datetime64[ns] to DatetimeIndex with no success. Here are my attempts:

import pandas as pd

my_data = [[1,'2019-05-01 04:00:00'], [2, '2019-05-01 04:01:00'], [3, '2019-05-01 04:02:00']]
test = pd.DataFrame(my_data, columns=['count', 'datetime'])
print(test.dtypes.value_counts())

# Attempt using pd.DateTimeIndex
test['datetime'] = pd.DatetimeIndex(test['datetime'])
print(test.dtypes.value_counts())

if isinstance(test['datetime'], pd.DatetimeIndex):
    print('Success')

# Attempt using pd.to_datetime without format string
test['datetime'] = pd.to_datetime(test['datetime'])
print(test.dtypes.value_counts())

if isinstance(test['datetime'], pd.DatetimeIndex):
    print('Success')

# Attempt using pd.to_datetime with format string
test['datetime'] = pd.to_datetime(test['datetime'], format='%Y-%m-%d %h:%m:%s')
print(test.dtypes.value_counts())

if isinstance(test['datetime'], pd.DatetimeIndex):
    print('Success')

I am using the latest version of pandas - 0.25.3 and am on python 3.7. Any constructive advice is well appreciated.


回答1:


You can cast an index as a datetime. Use set_index on your column, and then typecast.

import pandas as pd
​
my_data = [[1,'2019-05-01 04:00:00'], [2, '2019-05-01 04:01:00'], [3, '2019-05-01 04:02:00']]
test = pd.DataFrame(my_data, columns=['count', 'datetime'])
test.set_index('datetime').index.astype('datetime64[ns]')
DatetimeIndex(['2019-05-01 04:00:00', '2019-05-01 04:01:00',
               '2019-05-01 04:02:00'],
              dtype='datetime64[ns]', name='datetime', freq=None)


来源:https://stackoverflow.com/questions/59690099/convert-datetime64ns-column-to-datetimeindex-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!