Pandas數(shù)據(jù)分析之批量拆分/合并Excel
前言
筆者最近正在學(xué)習(xí)Pandas數(shù)據(jù)分析,將自己的學(xué)習(xí)筆記做成一套系列文章。本節(jié)主要記錄Pandas中數(shù)據(jù)的合并(concat和append)
將一個大的Excel等份拆成多個Excel將多個小Excel合并成一個大的Excel并且標(biāo)記來源
一、假造數(shù)據(jù)

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、將一個大Excel等份拆成多個Excel
- 使用df.iloc方法,將一個大的dataframe,拆分成多個小的dataframe
- 將使用dataframe.to_excel保存每個小的Excel
#1.計算拆分后的每個excel的行數(shù)
#這個大excel,會拆分給這幾個人
user_names=['xiao_shuai',"xiao_wang","xiao_ming","xiao_lei","xiao_bo","xiao_hong"]
#每個人的人數(shù)數(shù)目
split_size=total_row_count//len(user_names)
if total_row_count%len(user_names)!=0:
split_size+=1
split_size
#拆分成多個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]
#將每個子df存入到列表
df_subs.append((idx,user_name,df_sub))
#3. 將每個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)
2、合并多個小Excel到一個大Excel
- 遍歷文件夾,得到要合并的Excel文件列表
- 分別讀取到dataframe,給每個df添加一列用于標(biāo)記來源
- 使用pd.concat進(jìn)行df批量合并
- 將合并后的dataframe輸出到excel
#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:
#讀取每個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)
#給每個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)



總結(jié)
這就是pandas的DataFrame和存儲文件之間轉(zhuǎn)換的基本用法了,希望可以幫助到你。
到此這篇關(guān)于Pandas數(shù)據(jù)分析之批量拆分/合并Excel的文章就介紹到這了,更多相關(guān)Pandas批量拆分合并Excel內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
對Python的交互模式和直接運(yùn)行.py文件的區(qū)別詳解
今天小編就為大家分享一篇對Python的交互模式和直接運(yùn)行.py文件的區(qū)別詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06
Python中return函數(shù)返回值實(shí)例用法
在本篇文章里小編給大家整理的是一篇關(guān)于Python中return函數(shù)返回值實(shí)例用法,有興趣的朋友們可以學(xué)習(xí)下。2020-11-11
python opencv實(shí)現(xiàn)切變換 不裁減圖片
這篇文章主要為大家詳細(xì)介紹了python opencv實(shí)現(xiàn)切變換,不裁減圖片,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07
關(guān)于Python中的if __name__ == __main__詳情
在學(xué)習(xí)Python的過程中發(fā)現(xiàn)即使把if __name__ == ‘__main__’ 去掉,程序還是照樣運(yùn)行。很多小伙伴只知道是這么用的,也沒有深究具體的作用。這篇文字就來介紹一下Python中的if __name__ == ‘__main__’的作用,需要的朋友參考下文2021-09-09

