#按行數(shù)分割表格函數(shù) #問題 #1.如果有有一個十萬行表格,要錄入系統(tǒng),但是系統(tǒng)每次最多只能錄入500行? #解決問題: #1.按照指定的行數(shù)分割表格 #2.分割出來的表格按照序號命名 import pandas as pd import os def SplitExcel(file,num): file_dir='result' #創(chuàng)建目錄 if os.path.isdir(file_dir): os.rmdir(file_dir) else: os.mkdir(file_dir) n = 1 row_list = [] df = pd.DataFrame(pd.read_excel(file, sheet_name=0)) row_num = int(df.shape[0]) # 獲取行數(shù) if num >= row_num: #如果分割行數(shù)大于總行數(shù),報錯 raise Exception('too much!!') try: for i in list(range(num,row_num,num)): row_list.append(i) row_list.append(row_num) # 得到完整列表 except Exception as e: print (e) (name,ext)=os.path.splitext(file) #獲取文件名 for m in row_list: filename=os.path.join(file_dir,name+'-' + str(n) + '.xlsx') if m row_num: df_handle=df.iloc[m-num:m] #獲取n行之前 print (df_handle) df_handle.to_excel(filename , sheet_name='sheet1',index=False) elif m == int(row_num): remainder=int(int(row_num)%num) #余數(shù) df_handle=df.iloc[m-remainder:m] #獲取最后不能整除的行 df_handle.to_excel(filename , sheet_name='sheet1', index=False) n = n + 1 if __name__=='__main__': file= 'result.xls' SplitExcel(file,num=10)
一張83行的表格,去除表頭,一共82行,按照10行分割,一共要獲得9張表格,最后一張表格,應(yīng)該只有兩行,中間的表格,數(shù)據(jù)必須是連續(xù)的,
分割前
分割后
到此這篇關(guān)于python使用pandas按照行數(shù)分割表格的文章就介紹到這了,更多相關(guān)pandas按行分割表格內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!