将数据帧索引转换为日期时间

如何将字符串的熊猫索引转换为日期时间格式?

我的数据帧 df是这样的:

                     value
2015-09-25 00:46    71.925000
2015-09-25 00:47    71.625000
2015-09-25 00:48    71.333333
2015-09-25 00:49    64.571429
2015-09-25 00:50    72.285714

但是索引是 string 类型的,但是我需要一个 datetime 格式,因为我得到了这个错误:

'Index' object has no attribute 'hour'

使用时

df["A"] = df.index.hour
280725 次浏览

It should work as expected. Try to run the following example.

import pandas as pd
import io


data = """value
"2015-09-25 00:46"    71.925000
"2015-09-25 00:47"    71.625000
"2015-09-25 00:48"    71.333333
"2015-09-25 00:49"    64.571429
"2015-09-25 00:50"    72.285714"""


df = pd.read_table(io.StringIO(data), delim_whitespace=True)


# Converting the index as date
df.index = pd.to_datetime(df.index)


# Extracting hour & minute
df['A'] = df.index.hour
df['B'] = df.index.minute
df


#                          value  A   B
# 2015-09-25 00:46:00  71.925000  0  46
# 2015-09-25 00:47:00  71.625000  0  47
# 2015-09-25 00:48:00  71.333333  0  48
# 2015-09-25 00:49:00  64.571429  0  49
# 2015-09-25 00:50:00  72.285714  0  50

I just give other option for this question - you need to use '.dt' in your code:

import pandas as pd


df.index = pd.to_datetime(df.index)


#for get year
df.index.dt.year


#for get month
df.index.dt.month


#for get day
df.index.dt.day


#for get hour
df.index.dt.hour


#for get minute
df.index.dt.minute

You could explicitly create a DatetimeIndex when initializing the dataframe. Assuming your data is in string format

data = [
('2015-09-25 00:46', '71.925000'),
('2015-09-25 00:47', '71.625000'),
('2015-09-25 00:48', '71.333333'),
('2015-09-25 00:49', '64.571429'),
('2015-09-25 00:50', '72.285714'),
]


index, values = zip(*data)


frame = pd.DataFrame({
'values': values
}, index=pd.DatetimeIndex(index))


print(frame.index.minute)

Doing

df.index = pd.to_datetime(df.index, errors='coerce')

the data type of the index has changed to

dataframe information