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中本來就有字符串格式數據,這里可以更改為判斷是否為空字符串,稍微修改一下即可
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章:
