gpt4 book ai didi

Python Pandas to_clipboard() UnicodeEncodeError : 'ascii' codec can't encode character

转载 作者:太空狗 更新时间:2023-10-29 21:58:22 28 4
gpt4 key购买 nike

我想将数据框数据传递到剪贴板,以便粘贴到 Excel 中。问题是,字符 '\xe9' 导致编码问题,如下所示:

>>> df.to_clipboard()
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\pandas\util\clipboard.py", line 65, in winSetClipboard
hCd = ctypes.windll.kernel32.GlobalAlloc(GMEM_DDESHARE, len(bytes(text))+1)
TypeError: string argument without an encoding

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
df.to_clipboard()
File "C:\Python34\lib\site-packages\pandas\core\generic.py", line 1028, in to_clipboard
clipboard.to_clipboard(self, excel=excel, sep=sep, **kwargs)
File "C:\Python34\lib\site-packages\pandas\io\clipboard.py", line 98, in to_clipboard
clipboard_set(objstr)
File "C:\Python34\lib\site-packages\pandas\util\clipboard.py", line 68, in winSetClipboard
hCd = ctypes.windll.kernel32.GlobalAlloc(GMEM_DDESHARE, len(bytes(text, 'ascii'))+1)
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 543793: ordinal not in range(128)

我解码了这个字符,它是一个重音 é

>>> '\xe9'.encode().decode()
'é'

阅读 to_clipboard() 的文档后,我注意到它说:其他关键字被传递给to_csv。好的,所以对于“其他关键字”,我假设这意味着来自 to_csv() 的关键字参数-- 具体来说,我想使用 encoding='cp1252'

当我尝试这样做时,to_clipboard() 无法识别 encoding 关键字:

df.to_clipboard(encoding='cp1252')
File "C:\Python34\lib\site-packages\pandas\core\generic.py", line 1028, in to_clipboard
clipboard.to_clipboard(self, excel=excel, sep=sep, **kwargs)
File "C:\Python34\lib\site-packages\pandas\io\clipboard.py", line 95, in to_clipboard
objstr = obj.to_string(**kwargs)
TypeError: to_string() got an unexpected keyword argument 'encoding'

有没有办法将所有数据(ascii 和非 ascii)传递到剪贴板?

最佳答案

df.to_clipboard(df.to_csv(encoding='cp1252'))

只需使用指定的编码将其编码为 csv,然后将其扔到剪贴板上。

关于Python Pandas to_clipboard() UnicodeEncodeError : 'ascii' codec can't encode character,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32409440/

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