How to Save in .npy Format?

Npy Files

Ever come across a .npy file? In this article, we’ll go over the steps to save in npy format. NPY is Numpy’s binary data storage format.

Numpy is an essential module for carrying out data science operations efficiently. Importing, saving and processing of data takes up a major portion of the time in the field of Data Science. When it comes to importing and exporting data, CSV files are a good option.

However, sometimes you need to save data only to use it again in Python. For such cases, Numpy provides the .npy format.

Importing and exporting data from and to .npy files is more efficient as compared to other options.

Numpy offers numpy.save() method that lets you save files to .npy format. It only lets you save data that is in an array format. It converts the array to a binary file before saving. Ultimately it is this binary file that gets saved.

In this tutorial, we will use a numpy array and save in .npy format. We’ll also import the file next.

Let’s get started.

Save in npy format using Numpy save()

Let’s start by creating a sample array.

import numpy as np 
arr = np.arange(10)
print("arr :) 
print(arr)

To save this array to .npy file we will use the .save() method from Numpy.

np.save('ask_python', arr)
print("Your array has been saved to ask_python.npy")

Running this line of code will save your array to a binary file with the name ‘ask_python.npy’.

Output:

arr:
[0 1 2 3 4 5 6 7 8 9 10]
Your array has been saved to ask_python.npy

Import .npy File in Python

To load the data back into python we will use .load() method under Numpy.

data = np.load('ask_python.npy')
print("The data is:")
print(data)

The output comes out as :

The data is:
[0 1 2 3 4 5 6 7 8 9 10]

Conclusion

This tutorial was about saving data from an array in Python in a .npy binary file and loading it back to Python. Hope you had fun learning with us!