I am a bit puzzled, because this worked previously when I run the code 1-2 years ago.
I have a large structured numpy array with different data types and column names. I can save it with numpy.savetxt() if I provide a format string (fmt) that describes the data types of each column. However, if I want to save a selection of just a few columns via array[['col_name1', 'col_name2']] together with the fmt string for the two columns, I get the following error message: ValueError: fmt has wrong number of % formats: %i %i
Here an example.
Saving the entire array works:
import numpy as np
arr = np.zeros(3, dtype=[('w', int), ('x', float), ('y', int), ('z', "i8")])
np.savetxt('works.txt', arr, fmt="%i %06f %i %i")
Saving two columns of it doesn't:
import numpy as np
arr = np.zeros(3, dtype=[('w', int), ('x', float), ('y', int), ('z', "i8")])
np.savetxt('ValueError.txt', arr[['w','y']], fmt="%i %i")
This gives me the error message:
ValueError: fmt has wrong number of % formats: %i %i
I have scripts that do exactly the same with large structured arrays and they worked when I used this 1-2 years ago.
I have no clue what is going on. After making the column selection, the array dtype object has the additional attributes offsets and itemsize. Does this cause the error?
In [131]: arr
Out[131]:
array([(0, 0., 0, 0), (0, 0., 0, 0), (0, 0., 0, 0)],
dtype=[('w', '<i8'), ('x', '<f8'), ('y', '<i8'), ('z', '<i8')])
In [132]: arr[['w','y']]
Out[132]:
array([(0, 0), (0, 0), (0, 0)],
dtype={'names':['w','y'], 'formats':['<i8','<i8'], 'offsets':[0,16], 'itemsize':32})
How can I fix this? Thank you!