import re
import xlrd
import xlwt
import pandas as pd
import numpy as np
from xlutils.copy import copy
#######################################方法一###########################################
#xlrd——对excel进行读操作
#xlwt——对excel进行写操作
#xlutils——对excel读写操作整合
#如果要把数据写入已存在的excel,需调用lutils库配合使用
#打开已有Excel文件读取数据
rexcel = xlrd.open_workbook('D:\\DataSet\\gant半年退款数据.xls',
formatting_info=True)
#获取excel文件中的某张表
retable = rexcel.sheets()[0]
#该表的总行数
rows = rexcel.sheets()[0].nrows
#利用xlutils.copy从打开的xlrd的Book变量中,拷贝一份成为xlwt的Workbook变量
wrexcel =copy(rexcel)
#通过xlwt中的get_sheet方法获得某张表
table = wrexcel.get_sheet(0)
#利用正则表达式提取每行末尾的数字并填入原excel文件中
#xlwt对象的写方法,参数分别是行、列、值!
for i in np.arange(rows):
table.write(i,1,re.findall(r'\d+$',retable.cell(i,0).value))
#写完新数据后,最终save保存
wrexcel.save('D:\\Output_DataSet\\gant半年退款数据_处理后.xls')
#####################################方法二#############################################
data = pd.read_excel('D:\\DataSet\\gant半年退款数据.xls')
# str.extract()——可用正则从字符数据中抽取匹配的数据,只返回第一个匹配的数据
# Series.str.extract(pat, flags=0, expand=None)
# pat : 字符串或正则表达式
# flags : 整型,
# expand : 布尔型,是否返回DataFrame
data['尾数'] = data['宝贝标题'].str.extract(pat='GANT.*?(\d{5,10})',expand=True)
data.to_excel('D:\\Output_DataSet\\gant半年退款数据_处理后2.xls')
df = pd.read_excel('D:\\Output_DataSet\\gant半年退款数据_处理后2.xls')
print(df.head())
结果如图: