What is the numpy.save() Method in Python

Numpy.save() method is “used to store the input array in a disk file with npy extension(.npy).”

Syntax

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

Parameters

file:

File or filename to which the data is saved. If the file is a string or Path, the .npy extension will be appended to the file name if it does not already have one. If the file is a file object, then the filename is unchanged.

allow_pickle:

Allow saving object arrays using Python pickles. Reasons for disallowing pickles include security (loading pickled data can execute arbitrary code) and portability (pickled objects may not be loadable on different Python installations). Default: True.

fix_imports: 

Only helpful in forcing objects in object arrays on Python 3 to be pickled in a Python 2-compatible way.

arr: Array data to be saved.

Return value

It stores the input array in a disk file with npy extension(.npy).

Example 1: How to Use numpy.save() method

import numpy as np

a = np.arange(5)

# a is printed.
print("a is:")
print(a)

# The array is saved in the file npfile.npy
np.save('npfile', a)

print("The array is saved in the file npfile.npy")

Output

a is:
[0 1 2 3 4]
The array is saved in the file npfile.npy

You can see the npfile.npy file in your working directory.

Example 2: Reading the .npy file

You can read the .npy file using the np.load() function and print the content of the npy file in the console.

import numpy as np

# The array is loaded into data
data = np.load('npfile.npy')

print("The data is:")
print(data)

# Data is printed from geekfile.npy
print("The data is printed from npfile.npy")

Output

The data is:
[0 1 2 3 4]
The data is printed from npfile.npy

After running the example, you will see the new file in the directory with ‘npfile.npy ‘.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.