When you are using numpy.savetxt() function to save numy array into a text file, you my get this error: TypeError: Mismatch between array dtype (‘<U31’) and format specifier (‘%.18e %.18e %.18e’). In this tutorial, we will introduce to you on how to fix this error.
Look at this example:
import numpy as np data = np.array([[10, 20, 30], ['https://www.tutorialexample.com', 'python', 'programming']]) print(data) fname= 'data.csv' np.savetxt(fname, data)
In this example, we will save a 2-D numpy array into a csv file, Elements in numpy array are two types: integer and string.
Run this python script, we will get error like this:
Why this TypeError occurs?
As to numpy.savetxt() function.
numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='n', header='', footer='', comments='# ', encoding=None)
The parameter fmt is %.18e defaultly. %.18e can format number (float, integer), however, it can not format string data.
To understand numpy.savetxt(), you can read this tutorial.
Understand numpy.savetxt() for Beginner with Examples – NumPy Tutorial
How to fix this TypeError?
We can use %s to format integer and string.
Here is an example.
fname= 'data.csv' np.savetxt(fname, data, fmt = '%s')
Open data.csv, we will find content like:
10 20 30 https://www.tutorialexample.com python programming
Then this type error is fixed.