简体   繁体   English

使用python将多行列表写入csv文件

[英]writing a list to multiple rows into csv file using python

How to split following list to multiple rows (3 rows) and write in to a csv file using python. 如何将以下列表拆分为多行(3行)并使用python写入csv文件。

holidays = ['2017-01-01', "New Year's Day", 'NSW', '2017-01-02', "New Year's Day (Observed)", 'NSW', '2017-01-26', 'Australia Day', 'NSW', '2017-04-14', 'Good Friday', 'NSW', '2017-04-15', 'Easter Saturday', 'NSW']

Following code write all values to single column in a csv. 以下代码将所有值写入到csv中的单列中。

Title = ('date', 'name','state')

with open(fileName,"w") as output:
    writer = csv.writer(output,lineterminator='\n')
    for val in lstAll:
        writer.writerow([val])

A solution using pandas 使用pandas的解决方案

import pandas as pd

holidays = ['2017-01-01', "New Year's Day", 'NSW', '2017-01-02', "New Year's Day (Observed)", 'NSW', '2017-01-26', 'Australia Day', 'NSW', '2017-04-14', 'Good Friday', 'NSW', '2017-04-15', 'Easter Saturday', 'NSW']
col_titles = ('date', 'name','state')

data = pd.np.array(holidays).reshape((len(holidays) // 3, 3))

pd.DataFrame(data, columns=col_titles).to_csv("holidays.csv", index=False)

Where: 哪里:

  1. pd.np.array(holidays) converts holidays to a numpy.array pd.np.array(holidays)holidays转换为numpy.array
  2. .reshape((len(holidays) // 3, 3)) changes the structure of the array to three "columns" .reshape((len(holidays) // 3, 3))将数组的结构更改为三个“列”
  3. pd.DataFrame(data, columns=col_titles) creates a pandas.Dataframe from data and col_titles pd.DataFrame(data, columns=col_titles)创建一个pandas.Dataframe从数据和col_titles
  4. .to_csv("holidays.csv", index=False) saves the dataframe to a CSV file .to_csv("holidays.csv", index=False)将数据.to_csv("holidays.csv", index=False)保存到CSV文件

Content of holidays.csv : 内容holidays.csv

date,name,state
2017-01-01,New Year's Day,NSW
2017-01-02,New Year's Day (Observed),NSW
2017-01-26,Australia Day,NSW
2017-04-14,Good Friday,NSW
2017-04-15,Easter Saturday,NSW

Note that the index will not be included if you use index=False in to_csv . 请注意,如果在to_csv使用index=False ,则不会包含该索引。

You can use list slicing to process the list in chunks of 3: 您可以使用列表切片以3的块形式处理列表:

with open(fileName, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    for i in range(0, len(lst), 3)):
        writer.writerow(lst[i:i+3])

Here's a kind of verbose example that shows how the list interpretation works: 这是一个冗长的示例,显示了列表解释的工作方式:

with open('outfile.csv', 'w') as outfile:
    writer = csv.writer(outfile)
    rows = [[holiday, holidays[i+1], holidays[i+2]] for i, holiday in enumerate(holidays) if i % 3 == 0]
    for row in rows:
        writer.writerow(row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM