8

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?

3
  • 1
    savetxt isn't a member of the array type. Did you mean numpy.savetxt there? Commented Jul 9, 2013 at 21:29
  • By the way, it would really help if you showed what you want the expected output to look like, instead of making us guess. It's no coincidence that at least two different smart people failed to read your mind (or maybe two different smart people plus one who's only as smart as me; I'm not sure I guessed right either)… Commented Jul 9, 2013 at 21:57
  • @abarnert Thanks for your comments, I edited the post to fix both of those problems. Commented Jul 10, 2013 at 2:48

2 Answers 2

7

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Actually I do want the 1x8 format. Is it possible to get that?
1

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)

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.