Search code examples
pythonpandasexcelopenpyxl

Exporting dataframe to excel with indexes


I am exporting a dataframe to excel. I am using this piece of code:

with pd.ExcelWriter(path, engine='openpyxl', mode='w') as writer:   
            df.to_excel(writer, sheet_name=name, index=False)

I know using index=False removes the indexes in excel. However, I have a row index called 'Total' that displays totals for specific columns. Is there a way I can only display that one row index and exclude the rest?

If I use index=True my excel looks like this:

       A      B      
  1    foo    100    
  2    foo    200    
  3    foo    100    
  4    foo    200  
Total         600 

I want my excel to look like this:

       A      B      
       foo    100    
       foo    200    
       foo    100    
       foo    200  
Total         600 

Solution

  • Assuming the first "column" is the index, you can replace the number by None or empty strings with rename:

    with pd.ExcelWriter(path, engine='openpyxl', mode='w') as writer:   
        (df.rename(lambda x: '' if x.isdigit() else x) # or None
           .to_excel(writer, sheet_name=name, index=True)
        )
    

    Output:

    enter image description here