我有一个类似于这里提到的问题,但是建议的方法都对我无效。
我有一个中等大小的
但是这不起作用,因为我遇到了一个错误:
我有一个中等大小的
utf-8
.csv文件,其中包含许多非ascii字符。我正在通过某个列的特定值来分割该文件,然后我想将每个获得的数据框保存为保留字符的.xlsx文件。但是这不起作用,因为我遇到了一个错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 7: ordinal not in range(128)
以下是我尝试的方法:
- Using
xlsxwriter
engine explicitly. This doesn't seem to change anything. Defining a function (below) to change encoding and throw away bad characters. This also doesn't change anything.
def changeencode(data): cols = data.columns for col in cols: if data[col].dtype == 'O': data[col] = data[col].str.decode('utf-8').str.encode('ascii', 'ignore') return data
Changing by hand all the offensive chars to some others. Still no effect (the quoted error was obtained after this change).
Encoding the file as
utf-16
(which, I believe, is the correct encoding since I want to be able to manipulate the file from within the excel afterwards) doesn't help either.
我认为问题在于文件本身(因为2和3),但我不知道如何解决。非常感谢任何帮助。以下是文件的开头。
"Submitted","your-name","youremail","phone","miasto","cityCF","innemiasto","languagesCF","morelanguages","wiek","partnerCF","messageCF","acceptance-795","Submitted Login","Submitted From","2015-12-25 14:07:58 +00:00","Zózia kryś","test@tes.pl","4444444","Wrocław","","testujemy polskie znaki","Polski","testujemy polskie znaki","44","test","test","1","Justyna","99.111.155.132",
编辑
一些代码(其中一个版本,没有拆分部分):
import pandas as pd
import string
import xlsxwriter
df = pd.read_csv('path-to-file.csv')
with pd.ExcelWriter ('test.xlsx') as writer:
df.to_excel(writer, sheet_name = 'sheet1',engine='xlsxwriter')
df.to_excel(path, encoding='utf8')
了吗? - Stefan