How to read/write a Pandas dataframe with multiindex as CSV file

A pandas dataframe with a multiindex is a useful data structure to agglomerate the results of a parameter study .

To avoid assembling such a dataframe multiple times it might be necessary to write it as a file, e.g. as a simple CSV file. This is a one-liner:

my_dataframe.to_csv(output_path)

The only mandatory parameter is the file name (or path + file name) to which the data should be written. A list of further, optional parameters can be found in the official pandas documentation. The multiindex is written as additional columns with the corresponding parameter names in the header, e.g. ‘resolution’.

How to read the CSV file back into a multiindexed Pandas dataframe?

This is again a one-liner:

my_dataframe = pandas.dataframe.read_csv(file_name, index_col=list_of_index_columns)

where ’list_of_index_columns’ is a python list which contains the numbers of all columns containing the multiindex, e.g. [0, 1] if your multiindex consists of two parameters stored in the first two columns. Again, further optional parameters can be found in the official pandas documentation.

See also