![](/img/trans.png)
[英]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.