Search code examples
pythoncsvexport-to-csv

Write list of lists to CSV file. Putting sub-lists into individual columns


I've gathered a list of lists and I'd like to write each item into a CSV row.

But there are sublists that I would like to put in individual columns.

How can I write the below results into a csv with 2 rows and 4 columns (having [1,2,3] in one column).

outputcsv=r'C:\Users\out.csv'

results=[[11, 22, 33, [1, 2, 3]], 
         [44, 55, 66, [4, 5, 6]]]

with open(outputcsv, 'w') as f:
    for item in results:
        f.write("%s\n" % item)
        f.flush()
    


    

Solution

  • Use following code snippet:

    import pandas as pd
    cols = ['a', 'b', 'c', 'd']
    d = [dict(zip(cols, vals)) for vals in results]
    pd.DataFrame(d).to_csv('C:\Users\out.csv')
    

    In case you want to append to existing csv file, change last line to:

    pd.DataFrame(d).to_csv('C:\Users\out.csv', mode='a', header=False)
    

    This is how your dataframe looks:

        a   b   c          d
    0  11  22  33  [1, 2, 3]
    1  44  55  66  [4, 5, 6]