如何将以下列表拆分为多行(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']
以下代码将所有值写入csv中的单个列。
Title = ('date', 'name','state')
with open(fileName,"w") as output:
writer = csv.writer(output,lineterminator='\n')
for val in lstAll:
writer.writerow([val])
答案 0 :(得分:3)
使用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)
其中:
pd.np.array(holidays)
将holidays
转换为numpy.array
.reshape((len(holidays) // 3, 3))
将数组的结构更改为三个"列" pd.DataFrame(data, columns=col_titles)
从数据和col_titles pandas.Dataframe
.to_csv("holidays.csv", index=False)
将数据框保存为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
请注意,如果您在index=False
中使用to_csv
,则不会包含该索引。
答案 1 :(得分:0)
您可以使用列表切片以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])
答案 2 :(得分:0)
这是一个详细的例子,展示了列表解释的工作原理:
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)