3
list1 = [1,2,3]
list2 = [3,5,6]
list3 = [4,5,6]

I want output in csv file as:

A B C 
1 3 4
2 5 5
3 6 6

I tried using pandas as well as np.savetxt() but it doesnt work!

3 Answers 3

6

Use DataFrame contructor with to_csv:

pd.DataFrame({'A': list1, 'B': list2, 'C':list3}).to_csv('file.csv', index=False)

If want custom order of columns:

(pd.DataFrame({'A': list1, 'B': list2, 'C':list3}, columns=['B','A','C'])
   .to_csv('file.csv', index=False))
Sign up to request clarification or add additional context in comments.

Comments

1

An alternative if you do not want to use external libraries:

import csv
with open('foo.csv', "wb") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        writer.writerow(['A', 'B', 'C'])
        for i in range(0, len(list1)):
            writer.writerow([list1[i],list2[i],list3[i]])

Comments

-1

Try this:

np.savetxt('test.csv', np.c_[l1,l2,l3], delimiter=' ', header='A B C',fmt='%d',comments='')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.