Write 2 lists in 2 columns of a CSV file in python… here is a solution to the problem.
Write 2 lists in 2 columns of a CSV file in python
Let’s say I have 2 lists
a = [1,2,3]
b = [4,5,6]
I
want to write them in two columns of the CSV file, so when I open the Excel sheet, I see something like this:
col1 col2
1 4
2 5
3 6
What should I do?
I used zip(a,b)
but the result is stored in one column:
col1
1 4
2 5
3 6
Solution
The use of pandas
is very simple. Just:
import pandas as pd
And then:
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)
Basically, you’re building a data frame with a list and then saving it back to the .csv
. Hope this helps.