split pd dataframe to excel files based on a column value

Solutions on MaxInterview for split pd dataframe to excel files based on a column value by the best coders in the world

showing results for - "split pd dataframe to excel files based on a column value"
Noan
17 Jul 2019
1import pandas as pd
2    
3data = pd.read_excel('anyexcelfile.xlsx', engine='openpyxl') # creates a dataframe called 'data'; pick any spreadsheet you can add paths to 'x:/folder/subfolder/anyexcelfile.xlsx' to be explict. 
4
5grouped = data.groupby("Column Header Name") # change "Column Header Name" to the name of the column needed to categorise or group the rows in the dataframe, 
6
7keys = grouped.groups.keys() #create a dictionary list of the each group unique varibles in the specifed column of the dataframe.   
8
9print(keys) #a cheeky debug to check it's working
10
11for key in keys: #looping through each key 
12        splitdf = grouped.get_group(key) # creating a temporary dataframe with only the values of the current key. 
13        splitdf.to_excel(str(key)+".xlsx", engine='xlsxwriter') #write the temporary dataframe called 'splitdf' to an excel file named after the key. At the end of the loop the temporary dataframe 'splitdf' is overwritten for use with the next key. 
14