python 刪除空值且合并excel的操作
適用條件
1:excel表比較多
2:excel的數(shù)據(jù)量比較大,不然的話excel篩選&手動合并還是很舒服滴~
需求
取出【電話】列中不為空所對應的行的值并且將幾張表給合并起來
來來來,放代碼了!!
import xlrd
import pandas as pd
import openpyxl
target_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("")#有空格,填充函數(shù),填的空值。要加fillna,不然無法刪除空值所對應的行
sysptom = sheet2[sheet2['電話'] !=""]#篩選
sysptoms=pd.concat([sysptoms,sysptom])#兩個dataframe合并,相當于合并excel
print(type(sysptom))
sysptoms.to_excel(target_xls, index=False)#pandas寫入excel用.to_excel
print("ok")

補充:python 讀取excel數(shù)據(jù),遇到空單元格的處理方法
讀取excel表格時,經常遇到空單元格的情況,這時需要明確的是,空單元格在python中是什么格式,NULL?NAN還是什么?
在用 xlrd 函數(shù)讀入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.ncols
t = 0
im_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)
判斷該單元格數(shù)值是否為字符串,當然如果你的excel中本來就有字符串格式數(shù)據(jù),這里可以更改為判斷是否為空字符串,稍微修改一下即可
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章
Python利用hashlib實現(xiàn)文件MD5碼的批量存儲
這篇文章主要為大家詳細介紹了如何用Python和hashlib實現(xiàn)文件MD5碼的批量存儲功能,文中的示例代碼講解詳細,感興趣的小伙伴可以學習一下2023-05-05
Matplotlib animation模塊實現(xiàn)動態(tài)圖
這篇文章主要介紹了Matplotlib animation模塊實現(xiàn)動態(tài)圖,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-02-02
Python實現(xiàn)用手機監(jiān)控遠程控制電腦的方法
這篇文章主要介紹了Python實現(xiàn)用手機監(jiān)控遠程控制電腦的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-04-04

