【问题标题】:Getting an error importing Excel file into pandas selecting the usecols parameter选择 usecols 参数将 Excel 文件导入熊猫时出错
【发布时间】:2018-06-20 07:54:21
【问题描述】:

我正在尝试将数据从 Excel 文件导入 pandas,但在输入以下内容时出现错误:

energy = pd.read_excel('Indicators.xls',
                       'Energy', 
                       skiprows=17, 
                       skip_footer=38, 
                       usecols=['C','D','E','F'])

但我收到一条错误消息,指出 'C' 不在列表中。在 Excel 中评估 Excel 文件时,它显然有一个 C 列。大熊猫文档说明如下:

usecols : int 或列表,默认无

如果 None 则解析所有列,如果 int 则表示最后一列 被解析。如果 ints 列表则表示要列出的列号列表 解析。如果字符串则表示 Excel 列的逗号分隔列表 字母和列范围(例如“A:E”或“A,C,E:F”)。范围是 包括双方。

所以我只想将C 导入到F,所以我已经尝试了上述两个建议。

我收到以下错误:

ValueError: 'C' is not in list

不知道为什么这不起作用。有什么建议?

【问题讨论】:

  • 如果你省略了usecols 参数,你会在结果数据框中得到C 列吗?
  • 如果我省略 usecols,我不会得到 C,但使用整数列表作为列是可行的。
  • 当您省略 usecols 时,您认为应该标记为 C 的数据框中列的名称是什么?

标签: python excel pandas dataframe


【解决方案1】:

查看您正在使用的版本。如果此版本早于 0.21.0 版本,请尝试使用 parse_cols。

columns = 'A:L'
df = pd.read_excel(file_to_process, sheetname=sheetname, parse_cols=columns)

我对 usecols 有同样的问题。改成 parse_cols 后就可以正常工作了。

【讨论】:

  • 作为注释,您可以使用pd.__version__查看版本
【解决方案2】:

这对我来说很好用:

dataset=pd.read_excel('testfile.xlsx',usecols="C:F")

输入:

A  B  C  D  E  F G
1  1  1  1  1  1 1

输出:

C D E F
1 1 1 1

【讨论】:

    猜你喜欢
    • 2018-02-15
    • 2014-01-27
    • 2017-05-21
    • 2018-12-27
    • 2021-08-03
    • 2013-06-12
    • 2022-07-20
    • 1970-01-01
    • 2020-09-25
    相关资源
    最近更新 更多