如果在Python中的pandas DataFrame中显示中文字符串会怎么样?

时间:2015-03-05 19:19:25

标签: python encoding pandas

假设我有以下数据。即使我使用#coding = utf-8来定义默认编码,输出仍然显示我:???而不是中国字符串。

#coding=utf-8
import pandas as pd

df = pd.DataFrame({ '日期' : ['2015-01-07', '2014-12-17', '2015-01-21', '2014-11-19', '2015-01-17', '2015-02-26', '2015-01-04', '2014-12-20', '2014-12-07', '2015-01-06'],
                    '股票代码': ['600795', '600268', '002428', '600031', '002736', '600216', '000799', '601600', '601939', '000898']
                    })

print df

1 个答案:

答案 0 :(得分:1)

尝试添加

pd.options.display.encoding = sys.stdout.encoding

靠近文件顶部。默认情况下,pandas在编码字符串时使用utf-8对unicode进行编码。

Python将sys.stdout.encoding设置为它检测到您的控制台或终端正在使用的编码。


import sys
import pandas as pd

pd.options.display.encoding = sys.stdout.encoding

df = pd.DataFrame(
    {'日期' : ['2015-01-07', '2014-12-17', '2015-01-21', '2014-11-19', 
               '2015-01-17', '2015-02-26', '2015-01-04', '2014-12-20', 
               '2014-12-07', '2015-01-06'],
     '股票代码': ['600795', '600268', '002428', '600031', '002736', '600216', 
                  '000799', '601600', '601939', '000898']})

print(df)

请注意,即使您使用字符串定义了列,Pandas也会将它们转换为unicode:

In [158]: df.columns
Out[158]: Index([u'日期', u'股票代码'], dtype='object')

这就是为什么当您print(df) Pandas使用pd.options.display.encoding编码这些值时。