Reputation: 2475
Consider the following dataframe:
data = {'Col_A': [3, 2, 1, 0], 'Col_B': ['a', 'b', 'a', 'b']}
df = pd.DataFrame.from_dict(data)
I can create a dataframa a and write it to Excel as follows:
a = df[df.Col_B == 'a']
a
a.to_excel(excel_writer = 'F:\Desktop\output.xlsx', index = False)
I am looking for a way to write an Excel file, for each value of column B. In reality, there are hundreds of values for Col_B. Is there a way to loop through this?
Any help is greatly appreciated!
Regards,
M.
Upvotes: 2
Views: 524
Reputation: 75080
You can do:
for i in df.Col_B.unique():
df[df.Col_B.eq(i)].to_excel('F:\Desktop\output'+i+'.xlsx',index=False)
Upvotes: 3
Reputation: 862481
If need for each group separate excel file loop by groupby
object:
for i, a in df.groupby('Col_B'):
a.to_excel(f'F:\Desktop\output_{i}.xlsx', index = False)
If need for each group separate sheetname in one exel file use ExcelWriter
:
with pd.ExcelWriter('output.xlsx') as writer:
for i, a in df.groupby('Col_B'):
a.to_excel(writer, sheet_name=i, index = False)
Upvotes: 3