筆者最近正在學(xué)習(xí)Pandas數(shù)據(jù)分析,將自己的學(xué)習(xí)筆記做成一套系列文章。本節(jié)主要記錄Pandas中數(shù)據(jù)的合并(concat和append)
將一個(gè)大的Excel等份拆成多個(gè)Excel將多個(gè)小Excel合并成一個(gè)大的Excel并且標(biāo)記來(lái)源
work_dir="./datas" splits_dir=f"{work_dir}/splits" import os if not os.path.exists(splits_dir): os.mkdir(splits_dir) #0.讀取源Excel到Pandas import pandas as pd df_source=pd.read_excel(f"{work_dir}/1.xlsx") df_source.head() df_source.index df_source.shape total_row_count=df_source.shape[0] total_row_count
#1.計(jì)算拆分后的每個(gè)excel的行數(shù) #這個(gè)大excel,會(huì)拆分給這幾個(gè)人 user_names=['xiao_shuai',"xiao_wang","xiao_ming","xiao_lei","xiao_bo","xiao_hong"] #每個(gè)人的人數(shù)數(shù)目 split_size=total_row_count//len(user_names) if total_row_count%len(user_names)!=0: split_size+=1 split_size #拆分成多個(gè)dataframe df_subs=[] for idx,user_name in enumerate(user_names): #iloc的開始索引 begin=idx*split_size #iloc的結(jié)束索引 end=begin+split_size #實(shí)現(xiàn)df按照iloc拆分 df_sub=df_source.iloc[begin:end] #將每個(gè)子df存入到列表 df_subs.append((idx,user_name,df_sub)) #3. 將每個(gè)dataframe存入到excel for idx,user_name,df_sub in df_subs: file_name=f"{splits_dir}/articles_{idx}_{user_name}.xlsx" df_sub.to_excel(file_name,index=False)
#1.遍歷文件夾,得到要合并的Excel名稱列表 import os excel_names=[] for excel_name in os.listdir(splits_dir): excel_names.append(excel_name) excel_names #2分別讀取到dataframe df_list=[] for excel_name in excel_names: #讀取每個(gè)excel到df excel_path=f"{splits_dir}/{excel_name}" df_split=pd.read_excel(excel_path) #得到username username=excel_name.replace("articles_","").replace(".xlsx","")[2:] print(excel_name,username) #給每個(gè)df添加1列,即用戶名字 df_split["username"]=username df_list.append(df_split) #3.使用pd.concat進(jìn)行合并 df_merged=pd.concat(df_list) df_merged.shape df_merged.head() df_merged["username"].value_counts() #4.將合并后的dataframe輸出到excel df_merged.to_excel(f"{work_dir}/result_merged.xlsx",index=False)
這就是pandas的DataFrame和存儲(chǔ)文件之間轉(zhuǎn)換的基本用法了,希望可以幫助到你。
到此這篇關(guān)于Pandas數(shù)據(jù)分析之批量拆分/合并Excel的文章就介紹到這了,更多相關(guān)Pandas批量拆分合并Excel內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:三亞 湘西 安慶 葫蘆島 烏魯木齊 呼倫貝爾 銀川 呼倫貝爾
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Pandas數(shù)據(jù)分析之批量拆分/合并Excel》,本文關(guān)鍵詞 Pandas,數(shù)據(jù)分析,之,批量,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。