Jacques
Jacques

Reputation: 955

Pandas: Write dataframe into multiple sheets grouped by name

I have this dataframe:

Receipt Description Card Member Account Cost Data
200a apple adam 08203928 $2 need more apples
200a apple adam 08203928 $2 need more apples
20022a pear bob 3214 $7
202a orange alice 411423432 $8
202a orange alice 321321 $8
202a orange alice 3213121 $8

I have sorted my dataframe by the "card member" column.

I want to be able to create multiple new excel sheets with this data with each sheet being grouped by name like I currently have.

For example:

In the dataframe above "adam","alice" & "bob" would each have there own sheets containing just there data and not any others.

Upvotes: 0

Views: 741

Answers (1)

Narendra Prasath
Narendra Prasath

Reputation: 1531

You can try this:

xlsxwriter engine you need to install for creating Excel sheet.

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter(r"sample.xlsx", engine='xlsxwriter')

Grouped by Card and saved each dataframe in separate sheet.

for index, group_df in df.groupby("Card"):   
    group_df.to_excel(writer, sheet_name=str(index),index=False)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

Upvotes: 3

Related Questions