[英]Convert datetime64[ns] column to DatetimeIndex in pandas
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.我正在使用的一个包有一个先决条件,即数据框的索引需要是一个 Pandas DatetimeIndex。 So, I have been trying to convert a column of the data type datetime64[ns] to DatetimeIndex with no success.
因此,我一直在尝试将数据类型为 datetime64[ns] 的列转换为 DatetimeIndex,但没有成功。 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.我正在使用最新版本的 Pandas - 0.25.3 并且在 python 3.7 上。 Any constructive advice is well appreciated.
任何建设性的建议都非常感谢。
You can cast an index as a datetime
.您可以将索引转换为
datetime
。 Use set_index
on your column, and then typecast.在您的列上使用
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.