TypeError: Mismatch between array dtype ('<U32') and format specifier ('%.18e')

Viewed 7189

I am using np.savetxt for the first time, and I am trying to save two variables (a string and a float) in a file named "trial.csv" as follows:

import numpy as np

RT = 2.76197329736740
key_name = 'space'

print(RT,key_name)
# Save data in a CSV file named subj_data_file
np.savetxt("trial.csv", (RT,key_name), delimiter=',', header="RTs,Key_Name")

I got the following error:

TypeError: Mismatch between array dtype ('<U32') and format specifier ('%.18e')

I do not understand the meaning of both ('<U32') and ('%.18e'). As a matter of fact, I do not understand how to use fmt when I have floats, integers and strings ...

It is a simplified example, but concretely, I would have the RT values (floats) in one column "RTs" and the key_name (float) values in another column "Key_Name". I will create more columns later on, and although I provided one value for RT and one value for key_name in this example, there will be more RT values in the column "RTs" as well as key names in the column "Key_Name".

2 Answers

This happens because the default fmt argument in np.savetxt() is '%.18e' which is suitable for numbers (integers/floats). If you want to save strings as well, you need to change the fmt argument to be '%s'.

Also, you need to change the X shape to reflect the fact that it's one row with two columns. So, you need to change np.savetxt to be just like so:

np.savetxt("trial.csv", [[RT, key_name]], fmt="%s", delimiter=',', header="RTs,Key_Name")

This means that everything will be saved as string. So, the value 2.761.. won't be a float. You can load this file like so:

np.loadtxt("trial.csv",delimiter=',', dtype=str) #notice assiging dtype to str
import numpy as np

names  = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 ,  0.5678 ,  0.9123 ])

ab = np.zeros(names.size, dtype=[('key_name', 'U6'), ('RT', float)])
ab['key_name'] = names
ab['RT'] = floats

np.savetxt('trial.csv', ab, fmt="%10s , %10.3f", header="Keys_Names,RTs")
Related