0
0
NumPydata~5 mins

np.savez() for multiple arrays in NumPy

Choose your learning style9 modes available
Introduction

We use np.savez() to save many arrays into one file. This helps keep data organized and easy to load later.

You want to save multiple related arrays from a data analysis to reuse later.
You need to share several arrays with a teammate in one file.
You want to save arrays from different steps of a process together.
You want to store arrays for a machine learning model's inputs and outputs.
You want to save arrays without converting them to text files.
Syntax
NumPy
import numpy as np

np.savez(filename, array1, array2, ..., arrayN)

# Or with names:
np.savez(filename, name1=array1, name2=array2, ...)

The filename should end with .npz but it is optional.

If you give names, you can load arrays by those names later.

Examples
Saves two arrays without names. They will be saved as 'arr_0', 'arr_1' inside the file.
NumPy
import numpy as np

array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])

np.savez('data.npz', array1, array2)
Saves two arrays with names 'first' and 'second'. Easier to access later by these names.
NumPy
import numpy as np

array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])

np.savez('data_named.npz', first=array1, second=array2)
Saves an empty file with no arrays. Useful to create a placeholder file.
NumPy
import numpy as np

# Edge case: saving no arrays
np.savez('empty.npz')
Saves one array without a name. It will be saved as 'arr_0'.
NumPy
import numpy as np

single_array = np.array([10])

np.savez('single.npz', single_array)
Sample Program

This program creates two arrays, saves them into one file with names, then loads and prints them to show they are saved correctly.

NumPy
import numpy as np

# Create arrays
ages = np.array([25, 30, 35])
scores = np.array([88, 92, 95])

print('Before saving:')
print('Ages:', ages)
print('Scores:', scores)

# Save arrays with names
np.savez('people_data.npz', ages=ages, scores=scores)

# Load saved arrays
loaded_data = np.load('people_data.npz')

print('\nAfter loading:')
print('Ages:', loaded_data['ages'])
print('Scores:', loaded_data['scores'])
OutputSuccess
Important Notes

Time complexity is O(n) where n is total elements saved, because data is copied to disk.

Space complexity depends on the size of arrays saved.

Common mistake: forgetting to use names and then not knowing which array is which when loading.

Use np.savez() when you want to save multiple arrays in one file. Use np.save() for a single array.

Summary

np.savez() saves multiple arrays into one file for easy storage and sharing.

You can save arrays with or without names; names help when loading.

Loading the file gives access to each array by its name or default names like 'arr_0'.