gpt4 book ai didi

python - Pandas to_csv : ascii can't encode character

转载 作者:太空狗 更新时间:2023-10-29 21:12:27 26 4
gpt4 key购买 nike

我正在尝试读取数据帧并将其写入管道分隔文件。一些字符是非罗马字母(`、ç、ñ 等)。但是,当我尝试将重音符号写为 ASCII 时,它就崩溃了。

df = pd.read_csv('filename.txt',sep='|', encoding='utf-8')
<do stuff>
newdf.to_csv('output.txt', sep='|', index=False, encoding='ascii')

-------

File "<ipython-input-63-ae528ab37b8f>", line 21, in <module>
newdf.to_csv(filename,sep='|',index=False, encoding='ascii')

File "C:\Users\aliceell\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 1344, in to_csv
formatter.save()

File "C:\Users\aliceell\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\formats\format.py", line 1551, in save
self._save()

File "C:\Users\aliceell\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\formats\format.py", line 1652, in _save
self._save_chunk(start_i, end_i)

File "C:\Users\aliceell\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\formats\format.py", line 1678, in _save_chunk
lib.write_csv_rows(self.data, ix, self.nlevels, self.cols, self.writer)

File "pandas\lib.pyx", line 1075, in pandas.lib.write_csv_rows (pandas\lib.c:19767)

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

如果我将 to_csv 更改为具有 utf-8 编码,那么我将无法正确读取文件:

newdf.to_csv('output.txt',sep='|',index=False,encoding='utf-8')
pd.read_csv('output.txt', sep='|')

> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb4 in position 2: invalid start byte

我的目标是拥有一个保留重音符号和特殊字符的竖线分隔文件。

此外,是否有一种简单的方法可以找出 read_csv 中断的是哪一行?现在我不知道如何让它向我展示坏角色。

最佳答案

检查答案 here

这是一个更简单的解决方案:

newdf.to_csv('filename.csv', encoding='utf-8')

关于python - Pandas to_csv : ascii can't encode character,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41228697/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com