1

I have a pivot table generated using python code:

Date                             Grand Total
Name       1/2/2010   2/2/2010
Alice        5          6           11
bob          5          5           10 
Clarke       4          8           12
Dwayne       3          4           7

I want the columns 'Name' and 'Grand Total'to be written in new excel sheet. Can anyone help me on this Thank you!

Roy2012
  • 11,755
  • 2
  • 22
  • 35
Lann
  • 33
  • 4

1 Answers1

0

It would be nice to have the code for reproducing the dataframe. Nevertheless, I think I was able to reproduce your example.

 import pandas as pd
 df = df = pd.DataFrame({'Name': ['Alice', 'bob', 'Clarke', 'Dwayne', 'Alice', 'bob', 'Clarke', 'Dwayne', 'Alice'], 'Date': ['1/2/2010','1/2/2010','1/2/2010','1/2/2010','2/2/2010', '2/2/2010','2/2/2010','2/2/2010','2/2/2010'], 'N': [5,5,4,3,5,5,8,4,1]})
 df = df.pivot_table(index='Name', columns='Date', values='N', aggfun='sum')
 df['Grand Total'] = df.sum(axis=1)

As it is a pandas dataframe you can simply export to a CSV file by

 df['Grand Total'].to_csv('pivot_table.csv')

Or to Excel:

 df['Grand Total'].to_excel("name_of_the_file.xlsx", sheet_name='DisiredSheetName')

You can find existing documentation on Pandas to_excel

marz
  • 83
  • 5