繁体   English   中英

Python / Pandas:Excel CSV UTF-8 文件中的列标题问题

[英]Python / Pandas: problem with column headers from an Excel CSV UTF-8 file

这是我第一次在 Pandas 中尝试 UTF-8,所以可能是一个新手错误。

我在 Excel 中有一个简单的测试表,我将其保存为 UTF-8 CSV。 在 Linux 上查看带有“less”的文件给了我这个:

<U+FEFF>sample;chead
1;test

而“hexdump -C”这个:

00000000  ef bb bf 73 61 6d 70 6c  65 3b 63 68 65 61 64 0d  |...sample;chead.|
00000010  0a 31 3b 74 65 73 74 0d  0a                       |.1;test..|

到目前为止,很好,我会假设这是一个正确的 UTF-8 文件。

我现在想将该文件读入熊猫数据帧并检查第一列的名称是“样本”还是“探针”。

#!/usr/bin/env python3

import pandas as pd

df = pd.read_csv("sample1.csv", encoding="utf-8", sep=None, engine="python")

cols = [x.lower() for x in df.columns.values]
print("Columns:", cols)
print("Columns[0]:", cols[0])
print("type Columns[0]:", type(cols[0]))

# I expect this not to print, but it does
if cols[0] not in ["sample", "probe"]:
     print("Ouch, cols[0] is not 'sample' or 'probe'???")

上面程序的输出是:

Columns: ['\ufeffsample', 'chead']
Columns[0]: sample
type Columns[0]: <class 'str'>
Ouch, cols[0] is not 'sample' or 'probe'???

从输出的第一行我确实理解(以某种方式)cols[0] 值是 '\sample',但是由于通过 print() 语句的输出是“sample”,我不明白为什么“if”触发.

我需要更改什么才能使“if”语句起作用?

<U+FEFF>是字节顺序标记,参见https://en.wikipedia.org/wiki/Byte_order_mark

要使用这些文件读入 Pandas 中的文件,您可以按照https://github.com/pandas-dev/pandas/issues/4793 中的建议将编码设置为utf-8-sig

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM