0
0
NumPydata~5 mins

Why saving and loading matters in NumPy

Choose your learning style9 modes available
Introduction

Saving and loading data lets you keep your work safe and use it later without starting over.

You finish cleaning or preparing data and want to save it for future use.
You train a model and want to save the results to avoid retraining.
You want to share your data or results with others.
You need to pause your work and continue later without losing progress.
Syntax
NumPy
import numpy as np

# Save array to file
np.save('filename.npy', array)

# Load array from file
array = np.load('filename.npy', allow_pickle=False)
Use np.save to save a NumPy array to a file with .npy extension.
Use np.load to load the saved array back into your program.
Examples
This saves a simple array and loads it back, then prints it.
NumPy
import numpy as np

arr = np.array([1, 2, 3])
np.save('my_array.npy', arr)
loaded_arr = np.load('my_array.npy', allow_pickle=False)
print(loaded_arr)
This saves and loads a 2D array (matrix).
NumPy
import numpy as np

arr = np.array([[1, 2], [3, 4]])
np.save('matrix.npy', arr)
loaded_matrix = np.load('matrix.npy', allow_pickle=False)
print(loaded_matrix)
Sample Program

This program shows how to save a NumPy array to a file and load it back. It prints the loaded array to confirm it matches the original.

NumPy
import numpy as np

# Create a sample array
data = np.array([10, 20, 30, 40, 50])

# Save the array to a file
np.save('data_file.npy', data)

# Load the array from the file
loaded_data = np.load('data_file.npy', allow_pickle=False)

# Print loaded data
print(loaded_data)
OutputSuccess
Important Notes

Saving data helps avoid repeating long calculations or data preparation.

Files saved with np.save are easy to load and keep data exactly as it was.

Remember to use the same filename when loading the data you saved.

Summary

Saving and loading data keeps your work safe and reusable.

Use np.save and np.load to save and load NumPy arrays easily.

This saves time and helps share or continue your work later.