Saving a numpy array with mixed data

I have a numpy array where each value is a float followed by an integer, for example:

my_array = numpy.array([0.4324321, 0, 0.9437212, 1, 0.4738721, 0, 0.49327321, 0]) 

I would like to save it like this:

 0.4324321 0 0.9437212 1 0.4738721 0 0.49327321 0 

But if I call:

 numpy.savetxt('output.dat',my_array,fmt='%f %i') 

I get an error message:

 AttributeError: fmt has wrong number of % formats. %f %i 

How can i fix this?

+7
python numpy io
source share
2 answers

Your real problem is that listing an array of 1D 8 elements gives you 8 rows of 1 column (or, if you force things, 1 row of 8 columns), not 4 rows of 2 columns. Thus, you can specify only one format (or, if you force things, 1 or 8 formats).

If you want to display this in 4x2 format instead of 1x8, you need to change the matrix first:

 numpy.savetxt('output.dat', my_array.reshape((4,2)), fmt='%f %i') 

This will give you:

 0.432432 0 0.943721 1 0.473872 0 0.493273 0 

The documents are a bit confusing, since they devote most of the wording to working with complex numbers instead of simple floats and ints, but the basic rules are the same, you specify either one qualifier or qualifier for each column (the intermediate case of specifying real and imaginary parts for each column does not matter )


If you want to write it in 1 row of 8 columns, you first need to change it to something with 1 row of 8 columns instead of 8 rows.

And then you need to specify 8 formats. It is not possible to tell numpy to “repeat these two formats four times,” but it is quite easy to do without numpy:

 numpy.savetxt('output.dat', my_array.reshape((1,8)), fmt='%f %i ' * 4) 

And it gives you:

 0.432432 0 0.943721 1 0.473872 0 0.493273 0 
+7
source share

The problem is that savetxt() will print one line for each array entry. You can force the 2D-array to create a new axis and then print the format (1x8) :

 numpy.savetxt('output.dat', my_array[numpy.newaxis,:], fmt='%f %i'*4) 
+1
source share

All Articles