[英]How to merge multiple sheets in a single workbook using Python when the first column is named differently across the workbook
[英]How to Split data into multiple sheets in one single workbook by country column using pandas
我正在嘗試從表中提取數據並加載到 excel 工作簿中,我想按國家/地區分隔數據,並且每個國家/地區數據將加載到帶有國家/地區名稱的每個工作表中。 但不幸的是,我沒有找到實現這種情況的確切邏輯。 我需要幫助解決錯誤和代碼來修復。下面是我的代碼。
import pandas as pd
with pd.ExcelWriter('meddevices_tm.xlsx') as writer:
dftm = pd.read_excel('')
dbconnect = pyodbc.connect("Driver={ODBC Driver 17 for SQL Server};Server=digital-dbserver.database.windows.net;Database=gdmd-db;uid=adm;pwd=gr!")
tsql= 'select [Franchise Name],[Prod Number],[Product Description],[Net Content],[Net Content UOM],[Product Type],[Base Unit Indicator],[Dispatch Unit Indicator],[Invoice Unit Indicator],[Ordering Unit Indicator],[Country] from [dbo].[onews_med_devices] '
cursor= dbconnect.cursor()
dftm =pd.read_sql(tsql,dbconnect)
dftm = pd.read_excel('Med Devices0818.xlsx')
split_values = dftm['Country'].sort_values().unique()
print(split_values)
for value in split_values:
print (value)
(dftm.query(f'Country == {value}').drop(columns='Country').copy().to_excel(excel_writer=writer,sheet_name=f'Country{value}',index=False))
您可以使用groupby
for country, filtered_df in dftm.groupby('Country'):
filtered_df.to_excel(...
這將返回每個國家/地區的過濾數據框,您可以將其保存到所需位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.