Search code examples
pythondataframecsvexport-to-csv

Saving each DataFrame column to separate CSV files


I have some dataframes, one of them is the following:

L_M_P = pd.read_csv('L_M_P.csv')  # dimensions 17520x33

I would like to be able to save each column as an independent csv file, without having to do it manually as follows:

L_M_P[:,0].to_csv('column0.csv')
L_M_P[:,1].to_csv('column1.csv')
...

In that case, I would have 33 new '.csv' files, each with dimensions 17520x1.


Solution

  • You can iterate through columns and write it to files.

    for column in df.columns:
        df[column].to_csv(column + '.csv')
    

    Note: Assuming language to be python as the question has pd mentioned in it and all mentioned code is part of pandas