2

I am creating list for each data items, I have following data structure and at the end of iteration have have 6 lists that contains data points. Each list has same length, I want to generate each list as a column of csv file

Example:

columnOfList1, columnOfList2...

this is my code that generate multiple list of data: what I can't figureout is to generate csv file.

for (fn1, lst1), (fn2, lst2) in product(dict1.iteritems(), dict2.iteritems()):
    for vector1, vector2 in zip(lst1, lst2):
2
  • are you having trouble with the csv module, writing to a file, or organizing your data? Commented Aug 14, 2012 at 2:26
  • NameError: name 'product' is not defined. (I assume you're talking about itertools.product, but would you please put it in your question? Commented Aug 14, 2012 at 2:29

3 Answers 3

4

As you told, each list have the same length. Why do you don't do a "for" with this length?

Example:

for i in range(len(some_list)):
    print lst[i], lst2[i], lst3[i], lst4[i], lst5[i]
Sign up to request clarification or add additional context in comments.

1 Comment

why didn't i think of this :)
1

Converting rows to lists is just translation. It's simply done with zip:

>>> foo
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
>>> zip(*foo)
[(0, 0, 0, 0, 0), (1, 1, 1, 1, 1), (2, 2, 2, 2, 2), (3, 3, 3, 3, 3), (4, 4, 4, 4, 4)]

So you can probably just do

>>> lsts = [l[1] for l in product(yourdicts)]
>>> csvwriter.writerows(zip(*lsts))

Comments

1

You can use numpy.savetxt for this. First stack the arrays into columns:

>>> import numpy as np
>>> col1 = np.array([1,2,3])
>>> col2 = np.array([4,5,6])
>>> output = np.vstack((col1, col2)).T
>>> output
array([[1, 4],
       [2, 5],
       [3, 6]])

Then write it out. You can just pass a filename, but here I've used StringIO to show the output:

>>> from StringIO import StringIO
>>> s = StringIO()
>>> np.savetxt(s, output, delimiter=',', fmt='%.7g')
>>> print s.getvalue()
1,4
2,5
3,6

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.