Excel 保存过程中字符不正确

问题描述 投票:0回答:1

我正在创建一个新列和这个新文件并想要保存。但在 Excel 文件中,一列有一个字符。如何在保存过程中跳过此行或将行更改为正确的字符?

import pandas as pd

path = '/My Documents/Python/'
fileName = "test.xlsx"

# open the Excel file
ef = pd.ExcelFile(path+fileName)

# read the contents
df = pd.read_excel(path+fileName, sheet_name=ef.sheet_names[0])
print(df['Content'])
print(df['Engine'])

i = 1
for test in df['Content']:
    try:
        print(i)
        print(test)
    except:
        print("An exception occurred")
        break
    i += 1

df['Test'] = 'value'
df.to_excel('My Documents/Python/Test_NEW.xlsx')

错误信息

data, consumed = self.encode(object, self.errors)
    UnicodeEncodeError: 'utf-8' codec can't encode character '\ude7c' in position 470: surrogates not allowed
python excel pandas pycharm
1个回答
1
投票
df['Content'] = df['Content'].astype(str)
© www.soinside.com 2019 - 2024. All rights reserved.