python pandas将索引转换为日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40815238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:02:33  来源:igfitidea点击:

python pandas convert index to datetime

pythonpandas

提问by Runner Bean

How do i convert a pandas index of strings to datetime format

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

my dataframe 'df' is like this

我的数据框“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

but the index is of type string, but i need it a datetime format because i get the error

但索引是字符串类型,但我需要它的日期时间格式,因为我收到错误

'Index' object has no attribute 'hour'

when using

使用时

 df['A'] = df.index.hour

回答by Romain

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

回答by blue_note

You could explicitly createa DatetimeIndexwhen initializing the dataframe. Assuming your data is in string format

您可以在初始化数据框时显式创建a DatetimeIndex。假设您的数据是字符串格式

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)

回答by Muhammad Ammar Fauzan

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

我只是为这个问题提供了其他选项 - 您需要在代码中使用“.dt”:

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