【问题标题】:Convert datetime64[ns] column to DatetimeIndex in pandas将 datetime64[ns] 列转换为 Pandas 中的 DatetimeIndex
【发布时间】:2020-04-28 14:25:13
【问题描述】:

我正在使用的其中一个包有一个先决条件,即数据框的索引需要是 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。非常感谢任何建设性的建议。

【问题讨论】:

    标签: python pandas datetimeindex


    【解决方案1】:

    您可以将索引转换为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)
    

    【讨论】:

    • 这是我注意到的,虽然代码有效,但我注意到日期格式不正确。你也注意到这一点了吗? python 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)
    • 您在评论中的代码可能正常工作。默认情况下,使用set_index 不会设置现有test 数据帧的索引。您需要实际设置它或使用inplace=True。您的代码本质上是将[0,1,2] 转换为日期时间。
    猜你喜欢
    • 2020-11-05
    • 1970-01-01
    • 2017-01-05
    • 2022-08-15
    • 2016-11-25
    • 2023-03-09
    • 2019-03-29
    • 2019-05-22
    • 1970-01-01
    相关资源
    最近更新 更多