PANDAS確定自動讀取EXCEL文件的header(繞過開頭的合並單元格,找字段名所在行數作為header)


    工作中經常需要處理大量的EXCEL文件入數據庫,但很多人做表格第一行都是合並的表格名稱,並且合並的行數不確定(即pandas read_excel時,多個文件的header不能確定),下面的def get_head可以自動判斷header的值,下面的代碼可以實現刪掉一個文件夾里所有excel文件最上方的合並單元格。如下圖所示

 

     !!!!!注:下面的代碼如果前五行里出現了不在字段名內的數據,可能識別錯誤。

 1 # -*- coding:utf-8 -*-
 2 # 讀取當前目錄下所有excel文件,並且輸出第一行是excel的表頭
 3 import os
 4 import pandas as pd
 5 def get_head(df): # 根據df表第一個出現的非空字符最多的行數最為header的函數
 6     list_temp=[]
 7     for i in range(0,df.shape[0]):
 8         list_temp.append(df.iloc[i].count())
 9     return list_temp.index(max(list_temp))
10 
11 files= os.listdir('./')
12 for f in files:
13     if f.endswith('.xls') or f.endswith('.xlsx'):
14         df_sheetname=pd.read_excel(f,sheet_name=None,nrows = 1) #只讀一行確定有多少
15         excel_name=f.replace('.xlsx','').replace('.xls','')    # 去掉文件名后的xlsx或xls
16         for s in list(df_sheetname):
17             df=pd.read_excel(f,sheet_name=s,header=None,dtype='str',nrows = 5) #只取前五行判斷
18             head=get_head(df) # 使用函數得到 前五行里非空字符最多的行數(第一次出現的)
19             df=pd.read_excel(f,sheet_name=s,header=head,dtype='str') 
20             df.to_excel(excel_name+'_'+s+'_result.xlsx',index=False)
21             #df.to_csv
22             #df.to_sql 
23             print(excel_name+'_'+s+',OK!')
24 input("已經全部讀取成功,請關閉頁面")    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM