Pandas+openpyxl進(jìn)行Excel處理詳解
1. 讀取多個(gè) Excel 文件并合并
假設(shè)你有一個(gè)文件夾,里面包含多個(gè) Excel 文件,你想將這些文件合并成一個(gè) DataFrame。
import pandas as pd
import os
# 文件夾路徑
folder_path = 'path/to/your/excel/files'
# 獲取文件夾中的所有 Excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 創(chuàng)建一個(gè)空的 DataFrame 來(lái)存儲(chǔ)所有數(shù)據(jù)
all_data = pd.DataFrame()
# 逐個(gè)讀取每個(gè) Excel 文件并將數(shù)據(jù)追加到 all_data 中
for file in excel_files:
file_path = os.path.join(folder_path, file)
df = pd.read_excel(file_path)
all_data = pd.concat([all_data, df], ignore_index=True)
# 查看合并后的數(shù)據(jù)
print(all_data.head())
2. 批量處理多個(gè) Excel 文件
假設(shè)你需要對(duì)多個(gè) Excel 文件進(jìn)行相同的處理(例如,添加一列、過(guò)濾數(shù)據(jù)等)。
import pandas as pd
import os
# 文件夾路徑
folder_path = 'path/to/your/excel/files'
output_folder = 'path/to/output/folder'
# 確保輸出文件夾存在
os.makedirs(output_folder, exist_ok=True)
# 獲取文件夾中的所有 Excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 處理每個(gè) Excel 文件
for file in excel_files:
file_path = os.path.join(folder_path, file)
df = pd.read_excel(file_path)
# 添加一列
df['New_Column'] = 'Some Value'
# 過(guò)濾數(shù)據(jù)
filtered_df = df[df['Some_Column'] > 100]
# 保存處理后的數(shù)據(jù)
output_file_path = os.path.join(output_folder, file)
filtered_df.to_excel(output_file_path, index=False)
print("Processing complete.")3. 從多個(gè) Excel 文件中提取特定信息
假設(shè)你需要從多個(gè) Excel 文件中提取特定的信息(例如,某個(gè)特定單元格的數(shù)據(jù))。
import pandas as pd
import os
# 文件夾路徑
folder_path = 'path/to/your/excel/files'
# 獲取文件夾中的所有 Excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 存儲(chǔ)結(jié)果
results = []
# 從每個(gè) Excel 文件中提取特定信息
for file in excel_files:
file_path = os.path.join(folder_path, file)
df = pd.read_excel(file_path)
# 假設(shè)我們需要提取第一行第一列的數(shù)據(jù)
specific_value = df.iloc[0, 0]
# 將結(jié)果存儲(chǔ)在一個(gè)列表中
results.append((file, specific_value))
# 打印結(jié)果
for file, value in results:
print(f"File: {file}, Specific Value: {value}")
4. 使用 openpyxl 處理多個(gè) Excel 文件
如果你需要更細(xì)粒度地控制 Excel 文件(例如,修改特定單元格、格式化等),可以使用 openpyxl 庫(kù)。
import openpyxl
import os
# 文件夾路徑
folder_path = 'path/to/your/excel/files'
output_folder = 'path/to/output/folder'
# 確保輸出文件夾存在
os.makedirs(output_folder, exist_ok=True)
# 獲取文件夾中的所有 Excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 處理每個(gè) Excel 文件
for file in excel_files:
file_path = os.path.join(folder_path, file)
workbook = openpyxl.load_workbook(file_path)
sheet = workbook.active
# 修改特定單元格
sheet['A1'] = 'New Value'
# 保存處理后的文件
output_file_path = os.path.join(output_folder, file)
workbook.save(output_file_path)
print("Processing complete.")5. 合并多個(gè) Excel 文件到一個(gè)工作簿的不同工作表
假設(shè)你有多個(gè) Excel 文件,并希望將它們合并到一個(gè)新的 Excel 工作簿中的不同工作表中。
import pandas as pd
import os
# 文件夾路徑
folder_path = 'path/to/your/excel/files'
output_file = 'merged_workbook.xlsx'
# 獲取文件夾中的所有 Excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 創(chuàng)建一個(gè)新的 ExcelWriter 對(duì)象
with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
# 處理每個(gè) Excel 文件并將數(shù)據(jù)寫(xiě)入不同的工作表
for file in excel_files:
file_path = os.path.join(folder_path, file)
df = pd.read_excel(file_path)
# 使用文件名作為工作表名稱(chēng)
sheet_name = os.path.splitext(file)[0]
# 寫(xiě)入數(shù)據(jù)
df.to_excel(writer, sheet_name=sheet_name, index=False)
print("Merging complete.")6. 批量處理多個(gè) Excel 文件并進(jìn)行數(shù)據(jù)清洗
假設(shè)你需要對(duì)多個(gè) Excel 文件進(jìn)行數(shù)據(jù)清洗,例如刪除空行、填充缺失值等。
import pandas as pd
import os
# 文件夾路徑
folder_path = 'path/to/your/excel/files'
output_folder = 'path/to/output/folder'
# 確保輸出文件夾存在
os.makedirs(output_folder, exist_ok=True)
# 獲取文件夾中的所有 Excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 處理每個(gè) Excel 文件
for file in excel_files:
file_path = os.path.join(folder_path, file)
df = pd.read_excel(file_path)
# 刪除空行
df.dropna(how='all', inplace=True)
# 填充缺失值
df.fillna(0, inplace=True)
# 保存處理后的數(shù)據(jù)
output_file_path = os.path.join(output_folder, file)
df.to_excel(output_file_path, index=False)
print("Data cleaning complete.")7. 從多個(gè) Excel 文件中提取特定列并合并
假設(shè)你需要從多個(gè) Excel 文件中提取特定列,并將這些列合并成一個(gè)新的 DataFrame。
import pandas as pd
import os
# 文件夾路徑
folder_path = 'path/to/your/excel/files'
# 獲取文件夾中的所有 Excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 創(chuàng)建一個(gè)空的 DataFrame 來(lái)存儲(chǔ)所有數(shù)據(jù)
all_data = pd.DataFrame()
# 逐個(gè)讀取每個(gè) Excel 文件并提取特定列
for file in excel_files:
file_path = os.path.join(folder_path, file)
df = pd.read_excel(file_path, usecols=['Column1', 'Column2'])
# 將提取的數(shù)據(jù)追加到 all_data 中
all_data = pd.concat([all_data, df], ignore_index=True)
# 查看合并后的數(shù)據(jù)
print(all_data.head())8. 批量重命名多個(gè) Excel 文件中的工作表
假設(shè)你需要批量重命名多個(gè) Excel 文件中的工作表名稱(chēng)。
import openpyxl
import os
# 文件夾路徑
folder_path = 'path/to/your/excel/files'
output_folder = 'path/to/output/folder'
# 確保輸出文件夾存在
os.makedirs(output_folder, exist_ok=True)
# 獲取文件夾中的所有 Excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 處理每個(gè) Excel 文件
for file in excel_files:
file_path = os.path.join(folder_path, file)
workbook = openpyxl.load_workbook(file_path)
# 重命名工作表
if 'OldSheetName' in workbook.sheetnames:
sheet = workbook['OldSheetName']
sheet.title = 'NewSheetName'
# 保存處理后的文件
output_file_path = os.path.join(output_folder, file)
workbook.save(output_file_path)
print("Sheet renaming complete.")9. 批量導(dǎo)出 Excel 數(shù)據(jù)到 CSV 文件
假設(shè)你需要將多個(gè) Excel 文件中的數(shù)據(jù)批量導(dǎo)出為 CSV 文件。
import pandas as pd
import os
# 文件夾路徑
folder_path = 'path/to/your/excel/files'
output_folder = 'path/to/output/csvs'
# 確保輸出文件夾存在
os.makedirs(output_folder, exist_ok=True)
# 獲取文件夾中的所有 Excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 處理每個(gè) Excel 文件
for file in excel_files:
file_path = os.path.join(folder_path, file)
df = pd.read_excel(file_path)
# 生成輸出文件路徑
base_name = os.path.splitext(file)[0]
output_file_path = os.path.join(output_folder, f'{base_name}.csv')
# 導(dǎo)出為 CSV 文件
df.to_csv(output_file_path, index=False)
print("Export to CSV complete.")10. 批量處理多個(gè) Excel 文件并進(jìn)行數(shù)據(jù)分析
假設(shè)你需要對(duì)多個(gè) Excel 文件進(jìn)行數(shù)據(jù)分析,例如計(jì)算總和、平均值等。
import pandas as pd
import os
# 文件夾路徑
folder_path = 'path/to/your/excel/files'
# 獲取文件夾中的所有 Excel 文件
excel_files = [f for f in os.listdir(folder_path) if f.endswith('.xlsx') or f.endswith('.xls')]
# 創(chuàng)建一個(gè)空的 DataFrame 來(lái)存儲(chǔ)所有數(shù)據(jù)
all_data = pd.DataFrame()
# 逐個(gè)讀取每個(gè) Excel 文件并將數(shù)據(jù)追加到 all_data 中
for file in excel_files:
file_path = os.path.join(folder_path, file)
df = pd.read_excel(file_path)
# 將數(shù)據(jù)追加到 all_data 中
all_data = pd.concat([all_data, df], ignore_index=True)
# 進(jìn)行數(shù)據(jù)分析
total_sum = all_data['Some_Column'].sum()
average_value = all_data['Some_Column'].mean()
# 打印結(jié)果
print(f"Total Sum: {total_sum}")
print(f"Average Value: {average_value}")到此這篇關(guān)于Pandas+openpyxl進(jìn)行Excel處理詳解的文章就介紹到這了,更多相關(guān)Pandas openpyxl處理Excel內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python多維列表總是只轉(zhuǎn)為一維數(shù)組問(wèn)題解決
這篇文章主要為大家介紹了python多維列表總是只轉(zhuǎn)為一維數(shù)組問(wèn)題解決實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
pyhton列表轉(zhuǎn)換為數(shù)組的實(shí)例
下面小編就為大家分享一篇pyhton列表轉(zhuǎn)換為數(shù)組的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04
Python實(shí)現(xiàn)將列表導(dǎo)出為Excel文件
在 Python 數(shù)據(jù)處理場(chǎng)景中,將列表(List)數(shù)據(jù)導(dǎo)出為 Excel 文件是高頻需求,本文將演示如何用 Free Spire.XLS for Python 實(shí)現(xiàn)列表轉(zhuǎn) Excel,感興趣的小伙伴可以了解下2025-12-12
python中b=a和b=a[:]區(qū)別小結(jié)
Python中b = a和b = a[:]有顯著區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2026-03-03
python Tcp協(xié)議發(fā)送和接收信息的例子
今天小編就為大家分享一篇python Tcp協(xié)議發(fā)送和接收信息的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07
Python?SQLAlchemy建立模型基礎(chǔ)關(guān)系模式過(guò)程詳解
SQLAlchemy是Python編程語(yǔ)言下的一款開(kāi)源軟件。提供了SQL工具包及對(duì)象關(guān)系映射(ORM)工具,使用MIT許可證發(fā)行。SQLAlchemy“采用簡(jiǎn)單的Python語(yǔ)言,為高效和高性能的數(shù)據(jù)庫(kù)訪(fǎng)問(wèn)設(shè)計(jì),實(shí)現(xiàn)了完整的企業(yè)級(jí)持久模型”。SQL數(shù)據(jù)庫(kù)的量級(jí)和性能重要于對(duì)象集合2022-12-12
kNN算法python實(shí)現(xiàn)和簡(jiǎn)單數(shù)字識(shí)別的方法
這篇文章主要介紹了kNN算法python實(shí)現(xiàn)和簡(jiǎn)單數(shù)字識(shí)別的方法,詳細(xì)講述了kNN算法的優(yōu)缺點(diǎn)及原理,并給出了應(yīng)用實(shí)例,需要的朋友可以參考下2014-11-11
最好的Python DateTime 庫(kù)之 Pendulum 長(zhǎng)篇解析
datetime 模塊是 Python 中最重要的內(nèi)置模塊之一,它為實(shí)際編程問(wèn)題提供許多開(kāi)箱即用的解決方案,非常靈活和強(qiáng)大。例如,timedelta 是我最喜歡的工具之一2021-11-11
詳解OpenCV執(zhí)行連通分量標(biāo)記的方法和分析
在本教程中,您將學(xué)習(xí)如何使用?OpenCV?執(zhí)行連通分量標(biāo)記和分析。具體來(lái)說(shuō),我們將重點(diǎn)介紹?OpenCV?最常用的連通分量標(biāo)記函數(shù):cv2.connectedComponentsWithStats,感興趣的可以了解一下2022-08-08

