利用python对excel进行数据剔除

时间:2023-03-09 05:26:16
利用python对excel进行数据剔除

需求分析:

  判断excel2表中的某个唯一字段是否满足条件,如果满足条件,就在excel1中进行查询,若存在excel中,就将该数据进行剔除。

python脚本的实现:

from __future__ import division
import pandas as pd #指定文件的路径
imputfile= 'C:\\Users\\Administrator\\Desktop\\excel1.xlsx' #原始表excel1
imputfile1= 'C:\\Users\\Administrator\\Desktop\\excel2.xls' #excel2
outputfile = 'C:\\Users\\Administrator\\Desktop\\result.xlsx' #结果

#读取excel1的数据到data
data = pd.read_excel(imputfile,encoding='utf-8')
ex_list = list(data.iloc[:,]) #将需要比对的字段转换为list形式 #读取excel2的数据到remove_data
remove_data = pd.read_excel(imputfile1,encoding='utf-8')

#找出excel2中需要筛选的字段满足的条件。如我这边需要满足的条件是:remove_data.iloc[i,7] =='成功'
remove_phone=[]
for i in range(,len(remove_data)):
if remove_data.iloc[i,] =='成功':
phone = remove_data.iloc[i,]
remove_phone.append(phone) #删除满足条件数据
for i in range(,len(remove_phone)):
ex_list.remove(remove_phone[i]) #将剔除后的数据赋值到new_data
new_data=data[data.iloc[:,].isin(ex_list)] #导出excel
new_data.to_excel(outputfile)

当然,像这种对excel的剔除数据也可以直接再excel中实现,比如我们先对excel2和excel1都按某一唯一字段进行排序,然后将excel2中需要筛选的结果复制在Excel1中,直接在excel1中根据该字段进行排序。但是这种方法有一个缺陷是,如果Excel2中的数据并不是完整的,那排序下来也会和excel1不一致。