小编Gia*_*chs的帖子

使用 usecols 时 pandas.read_excel 错误

我在从 Excel 文件读取数据时遇到一些问题。\nExcel 文件包含带有 unicode 字符的列名称。

\n\n

由于一些自动化原因,我需要将usecols参数传递给 pandas.read_excel 函数。

\n\n

问题是,当我不使用usecols参数时,数据加载时不会出现错误。

\n\n

这是代码:

\n\n
import pandas as pd\n\ndf = pd.read_excel(file)\ndf.colums\n\nIndex([u\'col1\', u\'col2\', u\'col3\', u\'col with unicode \xc3\xa0\', u\'col4\'], dtype=\'object\')\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果我使用 usecols:

\n\n
COLUMNS = [\'col1\', \'col2\', \'col with unicode \xc3\xa0\']\ndf = pd.read_excel(file, usecols = COLUMNS)\n
Run Code Online (Sandbox Code Playgroud)\n\n

我收到以下错误:

\n\n
ValueError: Usecols do not match columns, columns expected but not found: [\'col with unicode \\xc3\\xa0\']\n
Run Code Online (Sandbox Code Playgroud)\n\n

使用encoding = \'utf-8\'read_excel 作为参数并不能解决问题,并且还对 COLUMNS 元素进行编码。

\n\n

编辑:这里是完整的错误窗口。

\n\n …

python python-2.7 pandas python-unicode pandas-datareader

4
推荐指数
2
解决办法
4万
查看次数