Numpy arrays are efficient data structures for working with data in Python, and machine learning models in the scikit-learn library, and deep learning models like those in the Tensorflow and Keras library, expect the input data in the format of Numpy arrays and make the predictions in the format of Numpy arrays.
np.savetxt
The np.savetxt() function takes two required parameters which are file name and data and saves an array to a text file. To save a numpy array to a text file, use the numpy savetxt() method.
The numpy.savetxt() function helps the user to save the numpy array into a text file along with that we have used the format parameter in the function.
Syntax
numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='n', header='', footer='', comments='# ', encoding=None)
Parameters
fname:
If the filename ends in .gz, the file is automatically saved in the compressed gzip format. The loadtxt() function understands gzipped files transparently.
X:
[1D or 2D array_like] Data to be saved to the text file.
fmt:
A single format (%10.5f), a sequence of formats, or the multi-format string, e.g., ‘Iteration %d – %10.5f’, in which case delimiter is ignored.
delimiter:
String or character separating columns.
newline:
String or character separating lines.
header:
The string will be written at the beginning of the file.
footer:
The string will be written at the end of the file.
comments:
The string that will be prepended to the header and footer strings to mark them as comments. Default: ‘# ‘, as expected by For example, numpy.loadtxt() function.
encoding:
The encoding is used to encode the output file. It does not apply to output streams. If an encoding is something other than ‘bytes’ or ‘latin1′, you won’t be able to load the file in NumPy versions < 1.14. The default is ‘latin1′.
Example
In this example, we create the array using the np arange() function and then save that array in the txt file using the savetxt() function. See the following code.
import numpy as np x = np.arange(0, 20, 3) print("x is: ") print(x) # X is an array c = np.savetxt('npfile.txt', x, delimiter=', ')
Output
python3 app.py x is: [ 0 3 6 9 12 15 18]
So, our np array is printed on the console and also save in the npfile.txt.
The file will be saved in the same directory as our program file app.py
We can open the npfile.txt and read and print the content in Python.
Let’s read the text file content and print it in the console.
a = open("npfile.txt", 'r') # open file in read mode print("the file contains:") print(a.read())
Append the above code inside your programming file.
So, your whole file looks like below.
import numpy as np x = np.arange(0, 20, 3) print("x is: ") print(x) # X is an array c = np.savetxt('npfile.txt', x, delimiter=', ') a = open("npfile.txt", 'r') # open file in read mode print("the file contains:") print(a.read())
If you rerun the above code, you will see the output below.
x is: [ 0 3 6 9 12 15 18] the file contains: 0.000000000000000000e+00 3.000000000000000000e+00 6.000000000000000000e+00 9.000000000000000000e+00 1.200000000000000000e+01 1.500000000000000000e+01 1.800000000000000000e+01
TypeError: only length-1 arrays can be converted to Python scalars
In the savetxt() function, if the numpy arrays are not of equal dimension, an error occurs.
See the below code.
import numpy as np a = np.arange(0, 4, 1) b = np.arange(0, 6, 1) c = np.arange(0, 8, 1) print("a is: ") print(a) print("b is: ") print(b) print("c is: ") print(c) d = np.savetxt('npfile.txt', (a, b, c))
Output
a is: [0 1 2 3] b is: [0 1 2 3 4 5] c is: [0 1 2 3 4 5 6 7] Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/numpy/lib/npyio.py", line 1447, in savetxt v = format % tuple(row) + newline TypeError: only size-1 arrays can be converted to Python scalars During handling of the above exception, another exception occurred: Traceback (most recent call last): File "app.py", line 14, in <module> d = np.savetxt('npfile.txt', (a, b, c)) File "<__array_function__ internals>", line 5, in savetxt File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/numpy/lib/npyio.py", line 1449, in savetxt raise TypeError("Mismatch between array dtype ('%s') and " TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e')
In the above code, we have created three different arrays with three different sizes.
That is why first, TypeError occurred, which tells: only size-1 arrays can be converted to Python scalars.
Then the second TypeError is saying that Mismatch between array dtype(‘object‘) and format specifier (‘%.18e’).
Now, we can solve both of the TypeErrors bypassing one extra parameter called fmt.
You can save the array as a string with fmt=’ %s’.
See the following code.
import numpy as np a = np.arange(0, 4, 1) b = np.arange(0, 6, 1) c = np.arange(0, 8, 1) print("a is: ") print(a) print("b is: ") print(b) print("c is: ") print(c) d = np.savetxt('npfile.txt', (a, b, c), fmt='%s')
Output
a is: [0 1 2 3] b is: [0 1 2 3 4 5] c is: [0 1 2 3 4 5 6 7]
Now, you can see that our TypeErrors are solved, and we can also read the file and print the content in the console.
import numpy as np a = np.arange(0, 4, 1) b = np.arange(0, 6, 1) c = np.arange(0, 8, 1) print("a is: ") print(a) print("b is: ") print(b) print("c is: ") print(c) d = np.savetxt('npfile.txt', (a, b, c), fmt='%s') # open file in read mode print("the file contains:") print(a.read()) f = open("npfile.txt", 'r') print("the file contents are:") print(f.read())
Output
a is: [0 1 2 3] b is: [0 1 2 3 4 5] c is: [0 1 2 3 4 5 6 7] the file contents are: [0 1 2 3] [0 1 2 3 4 5] [0 1 2 3 4 5 6 7]
Use the numpy savetxt function to save the file in CSV.
Numpy savetxt function is used to save the file in CSV.
See the following code.
from numpy import asarray from numpy import savetxt # define data data = asarray([[0, 1, 2, 3, 4]]) # save to csv file savetxt('npfile.csv', data, delimiter=',', fmt='%s') f = open("npfile.csv", 'r') print("the csv file contents are:") print(f.read())
Output
The csv file contents are: 0,1,2,3,4
The array has a single row of data with 5 columns. We would expect this Data to be saved to a CSV file as a single row of data.
After running the example, we can inspect the contents of ‘npfile.csv ‘.
Also, we have read the csv file and printed the content in the console.
That is it for the np.savetxt() function.