1

I am trying to export some data from a complex numpy calculation to a text file so I can analyze it in Excel or something. The data type of the array I'm trying to export is slightly complicated and is defined like:

rowType = np.dtype([("SN", "S8"),
                    ("Freqs", np.uint16, (3,)),
                    ("Peaks", np.float32, (3,))])

So each "row" of this array is an 8-character string, a 3-element subarray of 16-bit integers, and a 3-element subarray of floats. I want to have one row per row in the text file, with tabs between each element of the subarrays. When I call savetxt to export the populated array, what would I supply to the fmt parameter to keep it from throwing an exception?

dpitch40
  • 2,621
  • 7
  • 31
  • 44
  • Possible duplicate of http://stackoverflow.com/questions/15881817/numpy-save-an-array-of-different-types-to-a-text-file – tiago Jul 31 '13 at 16:49

1 Answers1

4

The format code applies to each element in a row. Because you have arrays as elements, you can only control the format of the array and not the individual elements. You'd be better off printing the array line by line, as answered to this question.

If you must use savetxt, this would be the closest to your request:

np.savetxt(my_file, my_array, ['%s\t', '%s\t', '%s'])

However, if you change the data type to flatten the individual arrays, you can control the formatting of each element. Here is an example for a csv file:

new_dtype = [('SN', 'S8'), ('Freqs1', 'i'), ('Freqs2', 'i'), ('Freqs3', 'i'), 
             ('Peaks1', 'f'), ('Peaks2', 'f'), ('Peaks3', 'f')]
np.savetxt(my_file, my_array.astype(new_dtype), '%s,%i,%i,%i,%f,%f,%f')
Community
  • 1
  • 1
tiago
  • 22,602
  • 12
  • 72
  • 88
  • I got it to work by not using subarrays, but defining the datatype like this: rowType = np.dtype("S8,H,H,H,f,f,f"). Unfortunately I do still have to populate the rows individually. Not sure if there is a way around this. – dpitch40 Jul 31 '13 at 17:21