I am trying to pull data from a table and load into a excel workbook, i want to separate data by country and each country data will be loaded into each sheet with country name. But unfortunately i am didnt find exact logic to achieve this scenario. I need help here with errors and code to fix.Below is my code.
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))
You can use groupby
for country, filtered_df in dftm.groupby('Country'):
filtered_df.to_excel(...
This will return a filtered dataframe by each country, which you can save to a desired location.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.