<p>我有一个数据框,我想在Python2.7中的文件和记录器中写入几行。<code>print(dataframe.iloc[0:4])</code>输出数据框中列标题和前4行的漂亮网格。但是<code>logging.info(dataframe.iloc[0:4])</code>抛出:</p>
<blockquote>
<p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 87: ordinal not in range(128)</p>
</blockquote>
<p>这里是控制台的输出,可以直接工作到控制台,也可以通过<code>print()</code>(注意<code>²</code>):</p>
<pre><code>In[89]: d.iloc[0:4] OR print(d.iloc[0:4])
Out[89]:
ISO ID_0 NAME_0 ID_1 NAME_1 ID_2 NAME_2 Area(km.²) Pop2001_Cen Pop2010_Cen HHold2010 Hhold_Size
0 ARG 12 Argentina 2 Ciudad Autónoma de Buenos Aires NaN NaN 203.0 2776138.0 2890151 1150134.0 2.512882
1 ARG 12 Argentina 2 Ciudad Autónoma de Buenos Aires 2001.0 Comuna 1 NaN 171975.0 205886 84468.0 2.437444
2 ARG 12 Argentina 2 Ciudad Autónoma de Buenos Aires 2002.0 Comuna 2 NaN 165494.0 157932 73156.0 2.158839
3 ARG 12 Argentina 2 Ciudad Autónoma de Buenos Aires 2003.0 Comuna 3 NaN 184015.0 187537 80489.0 2.329971
</code></pre>
<p>与<code>file.write(dataframe.iloc[0:4])</code>等一样,列标题之一包含非ascii字符。我尝试过<code>decode()</code>、<code>encode()</code>等各种变体,但无法避免这个错误。</p>
<p><code>print(d.iloc[0:4])</code>起作用,所以另一种方法是使用<code>print(d.iloc[0:4], file=f)</code>,但即使使用<code>from __future__ import print_function</code>我也会得到上述ascii编码错误。</p>
<p>复制此问题的其他方法是<code>logging.info('Area(km.²)')</code>或<code>'Area(km.²)'.decode()</code></p>
<p>如何呈现此数据帧?</p>
<p>[编辑:]</p>
<p>我还想从根本上理解我是如何在Python2.7中处理字符串编码/解码的——我已经花了很多时间来处理这个问题,因为这并不是我唯一一次遇到这个<code>UnicodeDecodeError</code>错误,我不知道什么时候会发生,我仍然只是在控制台上抛出修复程序来查看有什么问题,没有任何潜在的了解。</p>