在python的CSV文件的2列中写入2个列表 [英] Write 2 lists in 2 columns of CSV file in python
本文介绍了在python的CSV文件的2列中写入2个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个列表,比如
a = [1,2,3]
b = [4,5,6]
我想将它们写在CSV文件的两列中,所以当我打开Excel工作表时,我会看到类似这样的内容:
I want to write them in two columns in CSV file so when I open the excel sheet I see something like this :
col1 col2
1 4
2 5
3 6
我该怎么做?
我使用了 zip(a,b)
,但结果存储在一列中:
I used zip(a,b)
but the result is stored in one column:
col1
1 4
2 5
3 6
推荐答案
使用 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
.希望有帮助.
Basically you are building a dataframe with your lists and then save back to .csv
. Hope that helps.
这篇关于在python的CSV文件的2列中写入2个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文