[英]how to write lists to specific columns of csv file in python
我有一個嵌套列表,每個嵌套列表都有多個字符串:
[['http:/house.com/06','http:/google.com/09','http:6000.com'],['http:/house.com/04','http:/google.com/03','http:600.com', 'http://900.com],['http:/house.com/09','http:/google.com/076','http://rather.com']...]
我的目標是在第一列中獲取每個列表的第一個元素,並在第二和第三列中獲取其余元素
想要在csv文件中得到結果:
col1 col2 co3 col4
http:/house.com/06 http:/google.com/09 http:6000.com
http:/house.com/04 http:/google.com/03 http:600.com http://900.com
http:/house.com/09 http:/google.com/076 http://rather.com
有沒有辦法做到這一點?
分隔符不應在標題行和數據行中更改。 由於您在幾行中有一個空字符串,因此應該使用逗號分隔符。 試試吧:
pandas
: import pandas as pd
l1 = [['http:/house.com/06','http:/google.com/09','http:6000.com'],['http:/house.com/04','http:/google.com/03','http:600.com', 'http://900.com'],['http:/house.com/09','http:/google.com/076','http://rather.com']]
df = pd.DataFrame(data=l1, columns=['col1','col2','col3','col4']).fillna('')
df.to_csv('file1.csv', index=None)
這就是數據框的樣子:
csv
包: import csv
l1 = [['http:/house.com/06','http:/google.com/09','http:6000.com'],['http:/house.com/04','http:/google.com/03','http:600.com', 'http://900.com'],['http:/house.com/09','http:/google.com/076','http://rather.com']]
with open('file1.csv', 'w') as f:
rows = [['col1','col2','col3','col4']] + l1
writer = csv.writer(f)
writer.writerows(rows)
CSV文件列由COMMA(,)分隔,因此您可以迭代數據結構並將以下文本打印到文件中:
col1,col2,co3,col4
http:/house.com/06,http:/google.com/09,http:6000.com,
http:/house.com/04,http:/google.com/03,http:600.com,http://900.com
http:/house.com/09,http:/google.com/076,http://rather.com,
你可以通過嵌套的for循環實現這一點
for x in lst:
for y in x:
print y + ","
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.