Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply Filter in header row with pandas

Let say I have dataframe like this:

     col1    col2          col3
0    A        A_1          pass
1    A        A_2          pass
2    A        A_1          fail
3    A        A_1          fail
4    A        A_1          pass
5    A        A_2          fail

I want to save this dataframe to an excel file and apply Filter in the header "col1" "col2" "col3", so when I open the excel file the filter should be already applied in header.

I use this line to save it as an excel file but not with Filter applied:

df.to_excel('data.xlsx',index=False)

How can I do this? Desirable output

like image 658
user14073111 Avatar asked Oct 25 '25 18:10

user14073111


1 Answers

Try this:

import pandas as pd
from openpyxl import load_workbook

path = r'D:\temp\you.xlsx'
df.to_excel(path,index=False)

wb = load_workbook(path)
ws = wb.active
ws.auto_filter.ref = ws.dimensions
wb.save(path)
wb.close()
like image 200
Andreas Avatar answered Oct 28 '25 06:10

Andreas