What is Numpy Save? Explained with Examples

In this article, we will be discussing a critical Numpy function, numpy.save(). Numpy save allows us to store nd-arrays within a disk file using the .npy extension.

Before learning the function, let’s see what NumPy is.

The NumPy module (Numerical Python) deals with array types. A vital data type in Numpy is a ndarray. It has functions for working on various domains in mathematics.

Installing the Module

Numpy is not part of the Python Standard Library. Install the module manually via PIP using the following command.

Command for Mac/Linux/Windows
pip install numpy

Numpy is an open-source project available on GitHub.

About the Function – Numpy save

Numpy save stores the array into a disk file in the system in a .npy extension. Here’s the function syntax explained:

Complete Syntax 
numpy.save(file, arr, allow_pickle=True, fix_imports=True)

Parameters
file -  file/filename is the location to which the data is located. If the file is of string type, .npy extenstion will be added to the file name. Note the file objects are not saved with .npy extenstion

arr - The name of the array to be saved.

allow_pickle - Set to True by default. This allows saving the object arrays via Python Pickles. Python Pickles is used to serialize or deserialize the Python object structure. This parameter is optional. 

fix_imports - Expects a boolean value. Forces array objects to be pickled in a Python 2 comaptible way.

Returns
Returns input array within a disk file as .npy

Demonstration of Numpy save Function

Demo 1 – Saving the File

Using the .save() function, we will save an array.

import numpy as np

myArray = np.array([2,4,6,8,10])
print(myArray)

np.save('myFile', myArray)

Output

[ 2  4  6  8 10]
numpy save

Demo 2 – Opening The .npy File

Using the .load() function, we are opening the saved file.

import numpy as np

loadArray = np.load('myFile.npy')

print(loadArray)

Output

[ 2  4  6  8 10]

How To Save a file as CSV in Numpy

Method 1 – Using .tofile() function

Using the .tofile() function, we can write the Numpy array to a CSV file.

import numpy as np

myArray = np.array([2,4,6,8,10])
print(myArray)

myArray.tofile('myCSV.csv, sep = ',')

Output

[ 2  4  6  8 10]
numpy tofile

Method 2 – Using .savetext() function

Another solution is to use .savetext() function. The savetext function also allows saving Numpy arrays as CSV.

import numpy as np

myArray = np.array([2,4,6,8,10])
print(myArray)

np.savetxt("myCSV.csv", myArray, 
              delimiter = ",")

Output

[ 2  4  6  8 10]
numpy savetext

How to Save Numpy Array to a Text File

To save Numpy arrays into Text files, use numpy.savetext(). Let’s look at the following program.

import numpy as np

myArray = np.array([2,4,6,8,10])
print(myArray)

np.savetxt("myText.txt", myArray)

Output

[ 2  4  6  8 10]
numpy savetext text file

How to Save Numpy Array as an Image File

There are multiple ways to arrays as an Image file. Let’s refer to the following examples:

Using the imageio.imwrite() function

By passing RGB(Red, Green, Blue) Color codes as Numpy arrays, we export the array as the JPEG image file format. Here’s the implementation:

import imageio
import numpy as np

myArray = np.arange(0, 223322, 1, np.uint8)
myArray = np.reshape(array, (1024, 720))

imageio.imwrite('myImage.jpeg', myArray)

Output

numpy array save as image

Using the Image fromarray() function

fromarray creates an image memory from the array object. The image memory is located in the provided path and file name.

import numpy as np
from PIL import Image

myArray = np.arange(0, 230420, 1, np.uint8)
myArray = np.reshape(myArray, (1024, 720))

image = Image.fromarray(myArray)
image.save("myImage.jpeg")

Output

How To Save a Python Dictionary Using NumPy

With the help of numpy.save() function, we can save a Python dictionary into a file. To save the dictionary into a file (.npy), we must pass the file name and dictionary as parameters. Let’s look at the following program:

import numpy as np

phonePrices = { 'iPhone': 90000, 'Samsung': 30000, 'OnePlus': 60000, 'Oppo': 20000}
np.save('myDictionary.npy', phonePrices)

Output

numpy save dictionary in file

How To Save a Sparse Matrix in Python

With the help of .save_npz function, we can save a sparse matrix in .npz format.

Let’s look at the following program:

import scipy.sparse
import numpy as np
#Creating the sparse matrix
sparse_matrix = scipy.sparse.csc_matrix(np.array([[0, 0, 3], [0, 1, 0]]))
sparse_matrix

# Converting to array
sparse_matrix.toarray()
#Saving the file 
scipy.sparse.save_npz('mySparse.npz', sparse_matrix)

Output

numpy save sparse matrix

How To Save hdf5 file in Python Using Numpy

Using the h5py module, we can create an hdf5 file and store ndarrays into it.

import numpy as np
import h5py
myArray = np.random.random(size=(50,50))
my_h5f = h5py.File('data.h5', 'w')
my_h5f.create_dataset('my_Dataset', data=myArray)


Output

<HDF5 dataset "my_Dataset": shape (50, 50), type "<f8">
numpy save hdf5 file

How To Compress Numpy Arrays Using Algorithms like Gzip? Why doesn’t it work sometimes?

The Gzip Python module allows us to store Numpy objects into Gzip compressed files. Let’s see how we can store a Numpy file as gzip.

import gzip
import numpy as np

myFile = gzip.GzipFile("myArray.npy.gz", "w")
np.save(file=myFile, arr=myArray)
myFile.close()

Output

Numpy file as gzip

Note that all data may not be able to be compressed. For example, The noise in data is incompressible. However, the data which consists of noise will be compressed in a 1:1 ratio regardless of the compression algorithm unless it is manually removed.

FAQs

How do I save and load a NumPy array?

To save a Numpy array into a text file, use – numpy.savetext()
To load a Numpy array from a text file, use – numpy.loadtxt()

Does Numpy save() overwrite files?

Yes. When writing in a file from numpy, the file content can be overwritten only if the file already exists.

How do I save multiple NumPy arrays?

To save multiple arrays in the same format, use numpy.savez.

Conclusion

We have discussed the Numpy module and how to save its array type into various file formats, which include:

  • CSV (Comma Separated Values)
  • Text (.txt)
  • Image File Formats (JPEG, PNG)
  • hdf5 file
  • Gzip Compressed File

We have also reviewed how various types can be saved into the file mentioned above formats, such as:

  • Python Dictionaries
  • Sparse Matrices

This shows the versatility of the Numpy Module and how it’s beneficial in the field of numerical Python.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments