【问题标题】:Write 2 lists in 2 columns of CSV file in python在 python 的 2 列 CSV 文件中写入 2 个列表
【发布时间】:2018-10-23 19:06:52
【问题描述】:

假设我有 2 个列表

a = [1,2,3] 
b = [4,5,6]

我想将它们写在 CSV 文件的两列中,所以当我打开 excel 表时,我会看到如下内容:

col1              col2

1                  4

2                  5

3                  6

我该怎么做?

我使用了zip(a,b),但结果存储在一列中:

col1 

1 4

2 5

3 6

【问题讨论】:

    标签: python python-3.x list csv


    【解决方案1】:

    您需要使用csv.Dictwriter() 才能指定字段名称。

    import csv
    
    with open('numbers.csv', 'w', newline='') as csvfile:
        fieldnames = ['col1', 'col2']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for i, j in zip(a, b):
            writer.writerow({'col1': i, 'col2': j})
    

    或者您可以使用writerows 和列表推导来代替常规的for 循环:

    writer.writerows([{'col1': i, 'col2': j} for i,j in zip(a,b)])
    

    【讨论】:

      【解决方案2】:

      使用pandas 非常简单。只是:

      import pandas as pd
      

      然后:

      In [13]: df = pd.DataFrame({'col1':a, 'col2':b})
      
      In [14]: df
      Out[14]: 
         col1  col2
      0     1     4
      1     2     5
      2     3     6
      
      In [15]: df.to_csv('numbers.csv', index=False)
      

      基本上,您正在使用列表构建数据框,然后保存回.csv。希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 2018-11-19
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 2015-06-30
        • 2016-09-02
        • 2016-03-26
        • 2013-11-03
        相关资源
        最近更新 更多