Excel表中的单元格内容包含tab键,即'\t',将单元格的数字取出来,替换为空,经检查替换成功了,但无法写回到单元格中,保存的数据仍然含tab键,代码如下:
tempdata = tempdf[sheettitle].iloc[row] # sheettitle为字段名变量
tempdata = tempdata.replace('\t', '') # 进行替换
以上两步经print输出检查无误
tempdf[sheettitle].iloc[row] = tempdata # 回写
没有提示错误,但保存的数据还是原来的。
有一种替代方法就是用\s+正则替换。写成:df.num=df.num.astype(str).replace('\s+','',regex=True)。
import pandas as pd
#writer=pd.ExcelWriter('test3.xlsx',engine='openpyxl')
#df=pd.read_excel('test3.xlsx',sheet_name='Sheet1')
df=pd.DataFrame({'name':['a','b','c','d'],'num':['35 35','26 26','34 34','18 18']})
df['num']=df.num.str.replace('\s+','',regex=True)
print(df.num)
print(df)
有具体数据么 tempdf[sheettitle].iloc[row] = tempdata # 回写 这个只是重新取了值吧,没有改变原tempdf
不是的,是重新写到df中去,最后还要保存。