简体   繁体   中英

Creating a CSV file from multiple lists

I'm pretty new to Python and I'm struggling to save some variables in a csv file.

I have my output in two lists that I want to put into a csv file. One is a list of integers, the other is a list of floats.

Say my lists are:

foo = [1,2,3,4,5]
bar = [5.1, 10.1, 15.1, 20.1, 25.1]

I know how to make csv files from lists of integers:

import numpy
a = numpy.asarray([ [1,2,3,4,5], [6,7,8,9,10] ])
numpy.savetxt("dog.csv", a, delimiter=",")

But I can not simply replace the lists with foo and bar as it returns an error.Mainly because I don't think you can put multiple lists in asarray like this.

How can I create a CSV file with the two lists foo and bar as my two rows?

ANY help would be much appreciated.

EDIT: Thanks for your replies! After seeing how you wrote the line.

a = ... 

I discovered that I was making a syntax error with inputting the lists into asarray :P

Works for me with numpy 1.8:

In [32]: foo = [1,2,3,4,5]

In [33]: bar = [5.1, 10.1, 15.1, 20.1, 25.1]

In [34]: a = numpy.asarray([ foo,bar ])

In [35]: a
Out[35]:
array([[  1. ,   2. ,   3. ,   4. ,   5. ],
       [  5.1,  10.1,  15.1,  20.1,  25.1]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM