--人生不是赛场,梦想不容退场,学习编程成就更好的自己--
Python语言简洁生动,特别适合文科生学习入门IT世界,用几十行代码就能够做一个完整的爬虫脚本,开发效率杠杠的!短时间内即可解决工作和学习中碰到的棘手问题。(本人外语专业毕业,机缘巧合爱上编程,自学道路曲曲折折,痛并快乐!)在这里总结一下自学Python遇到的难点和重点,分享码过的代码和要点总结,希望能够给初学者一点启示和鼓励,同时愿意结交更多大神交流有助提升自己的水平。
今天分享一个特别简单和常见的实例,汇总同一文件夹中所有EXCEL数据(默认为每个EXCEL第一个SHEET),比如不同科目成绩结果,就如下截图所示:
今天主要利用的资源库是大名鼎鼎的pandas,主要通过concat方法来做批量汇总,废话不多说看看如何实现吧:
步骤1-切换到指定文件路径并读取所有XLSX文件
步骤2-定义读取EXCEL自定义函数并把文件批量读取和保存到一列表
步骤3-通过CONCAT方法进行批量合并然后保存为汇总数据
步骤4-把汇总数据保存
文本代码如下:
import pandas as pd
import time
import os
def Set_Work_Path(x):
try:
os.chdir(x)
route = os.getcwd()
print(route)
return route
except Exception:
print("No Result")
work_path = r"E:DATA21JUL21" #Use r to avoid error of number unreadable like 21
Set_Work_Path(work_path)
#define a name as 汇总数据 to get all datasets together
def Get_Dedicated_4Letter_File_List(x):
path = os.getcwd()
files = os.listdir(path) #print(files) #check all files name in the path
current_list = []
for i in range(0 ,len(files) ,1):
try:
if files[i][-4:] == x and files[i][:4] != "汇总数据":
current_list.append(files[i])
except Exception:
pass
return current_list
Current_Excel_list = Get_Dedicated_4Letter_File_List("xlsx")
print(Current_Excel_list)
#define a function to open excel file
def Open_Excel_Xlsx(x):
try:
data = pd.read_excel(x, header=0, index_col=None) #open the first sheet normally
return data
except Exception:
print("No Result")
#Define a list to hold all the excel data sets
Excel_Data_List = []
for i in range(0,len(Current_Excel_list),1):
Excel_Data_List.append(Open_Excel_Xlsx(Current_Excel_list[i]))
print("Show it!!")
print(Current_Excel_list[i])
#Get all data sets together
df = pd.concat(Excel_Data_List) #pd.concat([df1, df2])
df.dropna(axis=0, how="all", inplace=True)
print(df)
#Saving it into an Excel file
writer = pd.ExcelWriter("汇总数据.xlsx")
df.to_excel(writer, sheet_name="DATA", index=False)
writer.save()
show = "Time: %s Seconds" % time.perf_counter()+", Well Done!"
print(show)
print("Running is OVER!!")
END
我为人人,人人为我!!欢迎大家关注,点赞和转发!!!
~~人生不是赛场,梦想不容退场~~不断努力学习蜕变出一个更好的自己,不断分享学习路上的收获和感悟帮助他人成就自己!!!
页面更新:2024-05-15
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号