我在从 Excel 文件读取数据时遇到一些问题。\nExcel 文件包含带有 unicode 字符的列名称。
\n\n由于一些自动化原因,我需要将usecols参数传递给 pandas.read_excel 函数。
\n\n问题是,当我不使用usecols参数时,数据加载时不会出现错误。
\n\n这是代码:
\n\nimport 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\')\nRun Code Online (Sandbox Code Playgroud)\n\n如果我使用 usecols:
\n\nCOLUMNS = [\'col1\', \'col2\', \'col with unicode \xc3\xa0\']\ndf = pd.read_excel(file, usecols = COLUMNS)\nRun Code Online (Sandbox Code Playgroud)\n\n我收到以下错误:
\n\nValueError: Usecols do not match columns, columns expected but not found: [\'col with unicode \\xc3\\xa0\']\nRun Code Online (Sandbox Code Playgroud)\n\n使用encoding = \'utf-8\'read_excel 作为参数并不能解决问题,并且还对 COLUMNS 元素进行编码。
编辑:这里是完整的错误窗口。
\n\n …