这篇教程python 删除空值且合并excel的操作写得很实用,希望能帮到您。 适用条件1:excel表比较多 2:excel的数据量比较大,不然的话excel筛选&手动合并还是很舒服滴~ 需求取出【电话】列中不为空所对应的行的值并且将几张表给合并起来 来来来,放代码了!! import xlrdimport pandas as pdimport openpyxltarget_xls = "合并表1.xlsx"source_xls = ["全1.xlsx", "全2.xlsx","全3.xlsx",/ "全4.xlsx","全5.xlsx","全6.xlsx"]sysptoms=pd.DataFrame()for i in range(len(source_xls)): print(i)#了解打印进度 sheet2=pd.read_excel(source_xls[i]).fillna("")#有空格,填充函数,填的空值。要加fillna,不然无法删除空值所对应的行 sysptom = sheet2[sheet2['电话'] !=""]#筛选 sysptoms=pd.concat([sysptoms,sysptom])#两个dataframe合并,相当于合并excel print(type(sysptom)) sysptoms.to_excel(target_xls, index=False)#pandas写入excel用.to_excelprint("ok") 
补充:python 读取excel数据,遇到空单元格的处理方法 读取excel表格时,经常遇到空单元格的情况,这时需要明确的是,空单元格在python中是什么格式,NULL?NAN还是什么? 在用 xlrd 函数读入excel时,空单元格其实是空字符串'' 形式 因此处理方法就很简单啦,如下:infilename = r'D:/aajja.xlsx'workbook = xlrd.open_workbook(infilename)df = workbook.sheet_by_name('sheetname')num_rows = df.nrows - 1 # 我这里是第一行不要,所以跳过了num_cols = df.ncolst = 0im_data = np.zeros((num_rows, num_cols))for curr_row in range(1, num_rows+1): for curr_col in range(num_cols): rawVal = df.cell(curr_row, curr_col).value if isinstance(rawVal, str): im_data[curr_row - 1, curr_col] = np.nan else: im_data[curr_row - 1, curr_col] = float(rawVal) 其实重点就一句:if isinstance(rawVal, str) 判断该单元格数值是否为字符串,当然如果你的excel中本来就有字符串格式数据,这里可以更改为判断是否为空字符串,稍微修改一下即可 以上为个人经验,希望能给大家一个参考,也希望大家多多支持51zixue.net。如有错误或未考虑完全的地方,望不吝赐教。 python 根据excel中颜色区分读取的操作 python 在mysql中插入null空值的操作 |