无法将pandas数据帧转换为具有正确utf8编码的列表

2024-09-29 23:18:52 发布

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

我试图将Pandas数据帧转换为一个列表,这是可行的,但我在编码方面有一些问题。我希望有人能给我建议如何处理这个问题。现在,我正在使用python2.7。在

我正在加载一个excel文件,它加载正确。在

我使用以下代码,得到以下输出:

germanStatesExcelFile='German_States.xlsx'
ePath_german_states=(os.path.dirname(__file__))+'/'+germanStatesExcelFile
german_states = pd.read_excel(ePath_german_states)
print("doc " + str(german_states))

输出:

^{pr2}$

下一步是将此数据帧转换为列表,我使用以下代码执行此操作:

german_states = german_states['states'].tolist()

输出:

[u'baden-w\xfcrttemberg', u'bayern', u'hessen', u'rheinland-pfalz', u'saarland', u'nordrhein-westfalen']

看起来这个列表转换utf-8是不对的。所以我尝试了以下步骤:

german_states = [x.encode('utf-8') for x in german_states]

输出:

['baden-w\xc3\xbcrttemberg', 'bayern', 'hessen', 'rheinland-pfalz', 'saarland', 'nordrhein-westfalen']

我希望有以下输出:

['baden-württemberg', 'bayern', 'hessen', 'rheinland-pfalz', 'saarland', 'nordrhein-westfalen']

Tags: 数据列表excelgermanstatesbayernepathbaden
1条回答
网友
1楼 · 发布于 2024-09-29 23:18:52

如果字符串只包含ascii字符,可以尝试python内置的str,如下所示。这适用于您提供的字符串,但可能不一定如此。在

否则,对similar question有许多好的答案。在

german_states = [u'baden-w\xfcrttemberg', u'bayern', u'hessen', u'rheinland-pfalz', u'saarland', u'nordrhein-westfalen']

german_states = list(map(str, german_states))

# ['baden-württemberg', 'bayern', 'hessen', 'rheinland-pfalz', 'saarland', 'nordrhein-westfalen']

相关问题 更多 >

    热门问题