Answers for "Split pd dataframe to excel files based on a column value"

0

Split pd dataframe to excel files based on a column value

import pandas as pd
    
data = 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. 

grouped = 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, 

keys = grouped.groups.keys() #create a dictionary list of the each group unique varibles in the specifed column of the dataframe.   

print(keys) #a cheeky debug to check it's working

for key in keys: #looping through each key 
        splitdf = grouped.get_group(key) # creating a temporary dataframe with only the values of the current key. 
        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.
Posted by: Guest on September-01-2021

Code answers related to "Split pd dataframe to excel files based on a column value"

Python Answers by Framework

Browse Popular Code Answers by Language