【问题标题】:python pandas convert index to datetimepython pandas将索引转换为日期时间
【发布时间】:2018-10-30 09:17:33
【问题描述】:

如何将 pandas 字符串索引转换为日期时间格式

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

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

'Index' object has no attribute 'hour'

使用时

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

【问题讨论】:

  • df.index.to_datetime()df.index = pandas.to_datetime(df.index)(前者现已弃用)。
  • type(df.index[1]) 仍然返回 'str'
  • 上面的数据转换为datetime没有问题-type(df.index[1]) == pandas.tslib.Timestamp。其余数据框中是否有错误数据?
  • 您也可以指定格式和错误 kwag。 pandas.to_datetime 的文档将解释其余部分。

标签: python pandas


【解决方案1】:

它应该按预期工作。尝试运行以下示例。

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

【讨论】:

    【解决方案2】:

    您可以在初始化数据框时显式创建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)
    

    【讨论】:

    • Python3 仅供参考,您需要index, values = zip(*data.items())
    【解决方案3】:

    我只是为这个问题提供了其他选项 - 您需要在代码中使用“.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

    【讨论】:

      【解决方案4】:

      在做

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

      索引的数据类型已更改为

      【讨论】:

        猜你喜欢
        • 2021-07-18
        • 2017-07-11
        • 2020-11-06
        • 2016-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多