I have a numpy array where every value is a float followed by an integer, e.g.:
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:
AttributeError: fmt has wrong number of % formats. %f %i
How can I fix this?
Your real problem is that printing out a 1D 8-element array gives you 8 rows of 1 column (or, if you force things, 1 row of 8 columns), not 4 rows of 2 columns. So, you can only specify a single format (or, if you force things, either 1 or 8 formats).
If you want to output this in a 4x2 shape instead of 1x8, you need to reshape the array 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 docs are a little confusing, as they devote most of the wording to dealing with complex numbers instead of simple floats and ints, but the basic rules are the same. You specify either a single specifier, or a specifier for each column (the in-between case of specifying real and imaginary parts for each column isn't relevant).
If you want to write it in 1 row of 8 columns, first you need to reshape it into something with 1 row of 8 columns instead of 8 rows.
And then you need to specify 8 formats. There's no way to tell numpy "repeat these two formats four times", but that's pretty easy to do without numpy's help:
numpy.savetxt('output.dat', my_array.reshape((1,8)), fmt='%f %i ' * 4)
And that gives you:
0.432432 0 0.943721 1 0.473872 0 0.493273 0
The problem is that savetxt()
will print one row for each array entry. You can force a 2D-array
creating a new axis and then print the (1x8)
format:
numpy.savetxt('output.dat', my_array[numpy.newaxis,:], fmt='%f %i'*4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With