Skip to content
Advertisement

How to split a dataframe by unique groups and save to a csv

I have a pandas dataframe I would like to iterate over. A simplified example of my dataframe:

JavaScript

I would like to iterate over each unique gene and create a new file named:

JavaScript

For the above example I should get three iterations with 3 outfiles and 3 dataframes:

JavaScript

The resulting data frame contents split up by chunks will be sent to another function that will perform the analysis and return the contents to be written to file.

Advertisement

Answer

You can obtain the unique values calling unique, iterate over this, build the filename and write this out to csv:

JavaScript

A more pandas-thonic method is to groupby on 'Gene' and then iterate over the groups:

JavaScript
Advertisement