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?

1

1 Answer 1

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.