擅长:python、mysql、java
<p>Pandas允许指定编码,但不允许忽略错误而不自动替换有问题的字节。因此,没有“一刀切”的方法,而是根据实际的用例采用不同的方法。</p>
<ol>
<li><p>您知道编码,并且文件中没有编码错误。
很好:您只需指定编码:</p>
<pre><code>file_encoding = 'cp1252' # set file_encoding to the file encoding (utf8, latin1, etc.)
pd.read_csv(input_file_and_path, ..., encoding=file_encoding)
</code></pre></li>
<li><p>你不想被编码问题所困扰,只想加载那个该死的文件,不管某些文本字段是否包含垃圾。好的,您只需使用<code>Latin1</code>编码,因为它接受任何可能的字节作为输入(并将其转换为相同代码的unicode字符):</p>
<pre><code>pd.read_csv(input_file_and_path, ..., encoding='latin1')
</code></pre></li>
<li><p>您知道,大多数文件是用特定的编码编写的,但它也包含编码错误。一个真实的例子是一个用非UTF8编辑器编辑的UTF8文件,它包含一些不同编码的行。Pandas没有提供特殊的错误处理,但是Python<code>open</code>函数有(假设Python3),并且<code>read_csv</code>接受类似文件的对象。这里使用的典型错误参数是<code>'ignore'</code>,它只抑制有问题的字节,或者(最好)用Python的反斜杠转义序列替换有问题的字节:</p>
<pre><code>file_encoding = 'utf8' # set file_encoding to the file encoding (utf8, latin1, etc.)
input_fd = open(input_file_and_path, encoding=file_encoding, errors = 'backslashreplace')
pd.read_csv(input_fd, ...)
</code></pre></li>
</ol>