Reorganize code that to_csv is in the proper scope