将pandas中的datetime64[ns]列转换为DatetimeIndex

3
我正在处理的一个软件包有一个前提条件,即数据框的索引需要是 pandas 的 DatetimeIndex。因此,我一直在尝试将数据类型为 datetime64[ns] 的列转换为 DatetimeIndex,但一直没有成功。以下是我的尝试:
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')


我正在使用最新版本的pandas - 0.25.3,并且在Python 3.7上运行。欢迎提供任何有建设性的建议。
1个回答

2
你可以将索引转换为datetime。在列上使用set_index,然后进行类型转换即可。
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)

这是我注意到的,虽然代码可以运行,但我注意到日期格式不正确。你也注意到了吗?import pandas as pd from pecos.monitoring import PerformanceMonitoring 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]') test.index = pd.DatetimeIndex(test.index.values, dtype='datetime64[ns]', name='datetime', freq=None) - UGuntupalli
你在评论中的代码很可能已经按照预期工作了。使用 set_index 默认情况下不会设置现有 test 数据帧的索引。你需要实际设置它或使用 inplace=True。你的代码本质上是将 [0,1,2] 转换为日期时间。 - Nick Becker

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