Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

value error when using numpy.savetxt

Tags:

python

numpy

I want to save each numpy array (A,B, and C) as column in a text file, delimited by space:

import numpy as np

A = np.array([5,7,8912,44])

B = np.array([5.7,7.45,8912.43,44.99])

C = np.array([15.7,17.45,18912.143,144.99])

np.savetxt('test.txt', (A, B, C), fmt='%s %s %s')

But I got following error:

ValueError: fmt has wrong number of % formats: %s %s %s

How to solve it?

like image 359
puti Avatar asked Aug 23 '14 10:08

puti


1 Answers

np.savetxt('/tmp/test.txt', np.column_stack((A, B, C)), fmt='%s %s %s')

yields

5.0 5.7 15.7
7.0 7.45 17.45
8912.0 8912.43 18912.143
44.0 44.99 144.99

Note that fmt='%s' produces the same result.


If you try

np.savetxt('/tmp/test.txt', (A, B, C))

you'll see that NumPy is writing each 1-D array on a separate line -- i.e. horizontally. Since fmt='%s %s %s' is used as the format for each line, an error was raised since each line had 4 values.

We can get around that problem by passing a 2-D array, np.column_stack((A, B, C)) to np.savetxt.

like image 169
unutbu Avatar answered Oct 14 '22 02:10

unutbu