使用Unicode字符打印Pandas列

2024-03-29 08:26:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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中很好地打印数据帧,但是当我尝试在sublimitext(使用py3)中打印数据帧时,我遇到了一个错误。在

UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 73: ordinal not in range(128)

我到处寻找解决方案(并且在这个过程中了解了很多关于unicode的知识),但是我不知道如何在sublimitext中打印数据帧。在

任何帮助都将不胜感激。在


Tags: 数据noin名称pandas编码dfnames
1条回答
网友
1楼 · 发布于 2024-03-29 08:26:31

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]

相关问题 更多 >