python-写入或记录熊猫数据框的打印输出

我有一个数据框,希望在Python 2.7中将几行写入文件和记录器中. print(dataframe.iloc [0:4])输出标题和数据帧中前4行的漂亮网格.但是logging.info(dataframe.iloc [0:4])抛出:

UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xc2 in position 87: ordinal not in range(128)

这是控制台的输出,可以直接在控制台或通过print()使用(请注意“²”):

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

就像file.write(dataframe.iloc [0:4])一样,列标题之一包含一个非ASCII字符.我已经尝试了解码(),编码()等的各种形式,但无法避免此错误.

print(d.iloc [0:4])可以工作,所以另一种方法是使用print(d.iloc [0:4],file = f),但是即使从__future__ import print_function进行操作,我仍然遇到上述ascii编码错误.

复制此问题的其他方法是logging.info(‘Area(km.²)’)或’Area(km.²)’.decode()

如何渲染此数据框?

[编辑:]

我还想从根本上理解我如何处理Python 2.7中的字符串编码/解码-我已经为此付出了很多时间,因为这不是我唯一遇到UnicodeDecodeError错误的时间,不知道什么时候会发生,我仍然只是在控制台上进行修复以查看发生了什么,而对发生的事情没有任何基础的了解.

解决方法:

IIUC,当您写出数据帧的前n行时,您可以尝试通过encoding =’utf-8’:

df.head(n).to_csv('yourfileout.csv', encoding='utf-8')

相关文章

转载:一文讲述Pandas库的数据读取、数据获取、数据拼接、数...
Pandas是一个开源的第三方Python库,从Numpy和Matplotlib的基...
整体流程登录天池在线编程环境导入pandas和xrld操作EXCEL文件...
 一、numpy小结             二、pandas2.1为...
1、时间偏移DateOffset对象DateOffset类似于时间差Timedelta...
1、pandas内置样式空值高亮highlight_null最大最小值高亮背景...