【问题标题】:Pandas SetIndex with DatetimeIndexPandas 使用 DatetimeIndex 设置索引
【发布时间】:2021-05-28 18:20:33
【问题描述】:

我有一个包含以下内容的 csv 文件

Symbol, Date, Unix_Tick, OpenPrice, HighPrice, LowPrice, ClosePrice, volume,
AAPL, 2021-01-04 09:00:00, 1609750800, 133.31, 133.49, 133.02, 133.49, 25000
AAPL, 2021-01-04 09:01:00, 1609750860, 133.49, 133.49, 133.49, 133.49, 700
AAPL, 2021-01-04 09:02:00, 1609750920, 133.6, 133.6, 133.5, 133.5, 500

所以我尝试像这样使用 Date 创建一个 pandas 索引

import pandas as pd
import numpy as np

df = pd.read_csv(csvFile)
df = df.set_index(pd.DatetimeIndex(df["Date"]))

我得到 KeyError: 'Date'

【问题讨论】:

    标签: pandas datetimeindex


    【解决方案1】:

    这是因为文件不是严格用逗号分隔的,而是逗号加空格分隔的。

    您可以通过strip 删除列名中的空格:

    df = pd.read_csv(csvFile)
    
    df.columns = df.columns.str.strip()
    
    df = df.set_index(pd.DatetimeIndex(df["Date"]))
    

    或读取带有分隔符", "的CSV文件:

    df = pd.read_csv(csvFile, sep=", ")
    
    df = df.set_index(pd.DatetimeIndex(df["Date"]))
    

    【讨论】:

      【解决方案2】:

      问题很可能出在, 之后的空间中。您可以尝试使用自定义sep= 参数加载数据:

      df = pd.read_csv("a1.txt", sep=r",\s+", engine="python")
      df = df.set_index(pd.DatetimeIndex(df["Date"]))
      print(df)
      

      打印:

                          Symbol                 Date   Unix_Tick  OpenPrice  HighPrice  LowPrice  ClosePrice  volume,
      Date                                                                                                            
      2021-01-04 09:00:00   AAPL  2021-01-04 09:00:00  1609750800     133.31     133.49    133.02      133.49    25000
      2021-01-04 09:01:00   AAPL  2021-01-04 09:01:00  1609750860     133.49     133.49    133.49      133.49      700
      2021-01-04 09:02:00   AAPL  2021-01-04 09:02:00  1609750920     133.60     133.60    133.50      133.50      500
      

      【讨论】:

        猜你喜欢
        • 2018-03-13
        • 2016-12-05
        • 2016-05-07
        • 1970-01-01
        • 2019-11-09
        • 2015-04-04
        • 2021-08-19
        • 2020-08-06
        • 1970-01-01
        相关资源
        最近更新 更多