这是我第一次冒险进入Pandas的UTF-8,所以可能是一个新的错误。
我有一个简单的测试表,在Excel中,我保存为UTF-8 CSV.查看Linux上“更少”的文件,我可以看到以下内容:
<U+FEFF>sample;chead
1;test而“已转储-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值是'\ufeffsample',但是由于输出通过print()语句是"sample",我不明白为什么"if“触发。
为了使"if“语句工作,我需要更改什么?
发布于 2019-11-25 17:04:09
<U+FEFF>是一个字节顺序标记,参见https://en.wikipedia.org/wiki/Byte_order_mark。
要在熊猫中读取这些文件,您可以按照utf-8-sig中的建议将编码设置为https://github.com/pandas-dev/pandas/issues/4793。
https://stackoverflow.com/questions/59036599
复制相似问题