緒論
在數(shù)據(jù)分析工作中,嘗嘗需要處理多個不同月的excel文件,但無奈與excel文件的局限性,不能同時處理多個月的excel數(shù)據(jù),所以python的批量讀取excel文件就顯得十分重要,下面我將展示如何用python將每個月度的excel數(shù)據(jù)進行讀取并匯總處理和輸出。
一、加載包
############
###加載包###
############
#如果出現(xiàn)報錯,可使用pip install 包名 來進行下載
import os #導(dǎo)入查看文件路徑庫
import pandas as pd # 導(dǎo)入Pandas庫
import ntpath
from datetime import datetime
二、獲取文件夾路徑
最好excel的文件名就是按照日期排列,最后可以依據(jù)文件名來對匯總后的數(shù)據(jù)進行區(qū)分,如下圖
文章來源:http://www.zghlxwxcb.cn/news/detail-596648.html
###################
###查看并修改路徑##
###################
os.getcwd()
print(os.path.abspath('.'))
os.chdir("C:\\Users\\ALSC\\Desktop\\分析報表\\人員明細")#修改工作路徑
## 定義路徑,注意文件夾之間用“\\”最后要有個“\\”
path = os.path.abspath('.')
path
## 獲取所有文件的完整路徑名
all_files_path=[]
for root, dirs, files in os.walk(path, topdown=False):
if len(files) > 0:
each_foder_files=[os.path.join(root, x) for x in files]
all_files_path.extend(each_foder_files)
三、批量讀取數(shù)據(jù),并添加時間文章來源地址http://www.zghlxwxcb.cn/news/detail-596648.html
##############################
#####批量讀取數(shù)據(jù)、并添加時間#####
##############################
df = pd.DataFrame()
for f in all_files_path:
each_df = pd.read_excel(f, sheet_name="sheet1", engine="openpyxl")
name = ntpath.basename(f)
name = name.split(".")[0]
name = name.replace("年", "-").replace("月", "-").replace("日", "")
name = datetime.strptime(name, "%Y-%m-%d")
each_df.insert(loc=0, column="日期", value=name)
df = df.append(each_df)
df = df.iloc[:,0:17]
df = df[df["城市等級"].notna()]
df["省份"] = df["省份"].replace("上海", "上海市")
df["省份"] = df["省份"].replace("北京", "北京市")
df["省份"] = df["省份"].replace("天津", "天津市")
############
##輸出數(shù)據(jù)##
############
#最后輸出匯總?cè)藛T數(shù)據(jù)
df.to_excel("匯總?cè)藛T數(shù)據(jù).xlsx", sheet_name="Sheet1", index = False)
到了這里,關(guān)于python如何批量讀取一個文件夾里的所以excel文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!