Q:

group by to create multiple files

I have written a code using pandas groupby and its is working.
my question is how can I save each group in a excel sheet.
For example is you have group of fruits [ 'apple', 'grapes',.....'mango
']
I want to save apple in an excel and gapes in a different excel
import pandas as pd

df = pd.read_excel('C://Desktop/test/file.xlsx')
g = df.groupby('fruits')
for fruits, fruits_g in g:
        print(fruits)
        print(fruits_g)

Mango 
  name   id   purchase   fruits
1  john  877          2  Mango 

apple
  name   id   purchase  fruits
0   ram  654          5  apple
3  Sam   546          5  apple

BlueB
   name   id   purchase   fruits
7  david  767          9  black 

grapes
  name   id   purchase   fruits
2  Dan   454          1  grapes
4   sys  890          7  grapes

mango
  name   id   purchase  fruits
5  baka  786          6  mango

strawB
    name   id   purchase  fruits
6  silver  887          9  straw

How Can i Create an excel for each group of fruit?

A:

This can be accomplished using pandas.DataFrame.to_excel:
import pandas as pd

df = pd.DataFrame({
    "Fruit": ["apple", "orange", "banana", "apple", "orange"],
    "Name": ["John", "Sam", "David", "Rebeca", "Sydney"],
    "ID": [877, 546, 767, 887, 890],
    "Purchase": [1, 2, 5, 6, 4]
})

grouped = df.groupby("Fruit")

# run this to generate separate Excel files
for fruit, group in grouped:
    group.to_excel(excel_writer=f"{fruit}.xlsx", sheet_name=fruit, index=False)

# run this to generate a single Excel file with separate sheets
with pd.ExcelWriter("fruits.xlsx") as writer:
    for fruit, group in grouped:
        group.to_excel(excel_writer=writer, sheet_name=fruit, index=False)

