【问题标题】:KeyError despite definition of names at read_csv()尽管在 read_csv() 中定义了名称,但 KeyError
【发布时间】:2016-03-05 15:53:50
【问题描述】:

我正在尝试打印pandas.dataframe 的列。然而,尽管我使用pandas.read_csv() 中的names 参数显式分配了列名,但这仍然失败。

给定以下代码:

data = pd.read_csv(filename, sep='\t',
                   names=['Symbol', 'Date', 'Type', 'Value'],
                   index_col=[0])
print(data)

产生这个:

             Date      Type         Value
Symbol                                       
benchmark  2011-12-01       dax  1.422847e+08
benchmark  2011-12-02       dax  1.958363e+08
benchmark  2011-12-05       dax  1.922807e+08
benchmark  2011-12-06       dax  1.477339e+08
benchmark  2011-12-07       dax  1.354372e+08

但是这个: 打印(数据['日期'])

产生这个:

KeyError: 'Date'

据我所知,我正在做与 McKinney 在第 123 页上的 Python for Data Analysis 中描述的完全相同的事情。除了那个错误之外我没有得到任何输出。

数据格式如下:

Symbol\t2015-01-01\tType\tFloat_Value

我错过了什么?

【问题讨论】:

  • data.columns.tolist() 显示什么?
  • ['2011-12-01', 'dax', '142284736'] - 这很奇怪,因为我认为传递 names 会负责设置列名?
  • 更正:显示['Date', 'Type', 'Value'];我之前运行了一些其他测试代码,但我没有通过names

标签: python-3.x pandas dataframe anaconda


【解决方案1】:

确保您的列名中没有空格

您可以尝试改用sep='\s+'

data = pd.read_csv(filename, sep='\s+',
                   names=['Symbol', 'Date', 'Type', 'Value'],
                   index_col=[0])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    相关资源
    最近更新 更多