使用Unicode字符打印Pandas列

3
我有一个pandas数据框,其中只有一列包含Unicode编码的名称。
import pandas as pd

no_unicode = pd.Series(['Steve', 'Jason', 'Jake'])
yes_unicode = pd.Series(['tea', 'caf\xe9', 'beer'])

var_names = dict(no_unicode = no_unicode, yes_unicode = yes_unicode)

df = pd.DataFrame(var_names)

print(df)

我可以在ipython中正确地打印数据框,但是当我尝试在Sublimetext(使用py3)中打印数据框时,会出现错误。

UnicodeEncodeError: 'ascii'编解码器无法在第73个位置对字符'\xe9'进行编码:序数不在范围内(128)

我已经寻找了很多解决方案(并在此过程中学习了很多关于unicode的知识),但是我仍然无法弄清楚如何在Sublimetext中打印数据框。

非常感谢任何帮助。

1个回答

3

pandas.compat 中有一个非常有用的函数 u,可以将您的值转换为 Unicode 编码。

In [26]:
import pandas as pd
from pandas.compat import u
no_unicode = pd.Series(['Steve', 'Jason', 'Jake'])
#yes_unicode = pd.Series(['tea', 'caf\xe9', 'beer'])
yes_unicode = pd.Series(map(u,['tea', 'caf\xe9', 'beer']))
var_names = dict(no_unicode = no_unicode, yes_unicode = yes_unicode)
df = pd.DataFrame(var_names)
print(df)

  no_unicode yes_unicode
0      Steve         tea
1      Jason        café
2       Jake        beer

[3 rows x 2 columns]

我在这段代码中遇到了一个错误,"TypeError: object of type 'map' has no len()"。 - Anton
抱歉,没有注意到您正在使用python 3.x,更改为list(map(......))即可解决问题,在python 3中,map()返回一个map对象而不是一个list - CT Zhu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接