如果 Python 中的 pandas DataFrame 中显示中文字符串怎么办?
What if Chinese strings shown in the pandas DataFrame in Python
假设我有以下数据。即使我使用 #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
尝试添加
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
来 编码 这些值时。
假设我有以下数据。即使我使用 #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
尝试添加
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
来 编码 这些值时。