Writing Python lists to columns in csv

后端 未结 7 733

I have 5 lists, all of the same length, and I\'d like to write them to 5 columns in a CSV. So far, I can only write one to a column with this code:

with open         


        
7条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 19:39

    If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:

    import pandas as pd
    
    list1 = [1, 2, 3]
    list2 = [4, 5, 6]
    list3 = [7, 8, 9]
    
    df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')
    
    df.to_csv('file.csv', index=False)
    
    print(df)
    
       Col0  Col1  Col2
    0     1     4     7
    1     2     5     8
    2     3     6     9
    

提交回复
热议问题