Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

NumPy - Saving Arrays



Saving Arrays in NumPy

Saving arrays in NumPy refers to the process of writing NumPy arrays to files so they can be stored and later reloaded.

NumPy provides several methods for saving arrays in various formats, they are −

  • np.save() Function: Saves a single NumPy array to a file in binary .npy format.
  • np.savez() Function: Saves multiple NumPy arrays into a single file in compressed .npz format.
  • np.savez_compressed() Function: Similar to np.savez, but compresses the data for reduced file size.
  • np.savetxt() Function: Saves NumPy arrays to a text file with a specific format.

Saving Arrays to Text Files

Saving arrays to text files in NumPy is useful for exporting data in a human-readable format or for compatibility with other programs that require text input.

NumPy uses the np.savetxt() function to write arrays to text files in a specified format. It is designed to handle arrays with numerical data, but it can be adapted for various use cases through formatting options. Following is the syntax −

numpy.savetxt(fname, data, fmt=<format>, delimiter=<delimiter>, header=<header>, footer=<footer>, comments=<char>)

Where,

  • fname: Filename or file object where the data will be saved.
  • data: The array to be saved. It can be a one-dimensional or multi-dimensional array.
  • fmt: Format string for output. Defines how the data should be formatted (e.g., floating-point precision).
  • delimiter: String or character separating values in the file (e.g., comma for CSV, space for space-separated).
  • header: String to write at the beginning of the file. Useful for adding metadata or column names.
  • footer: String to write at the end of the file. Can be used for additional information.
  • comments: String indicating the start of a comment. Default is #.

Example

In the following example, we are saving a 2D NumPy array to a text file using np.savetxt() function −

import numpy as np

# Create an array
array = np.array([[1, 2, 3], [4, 5, 6]])

# Save the array to a text file
np.savetxt('data.txt', array, fmt='%d', delimiter=',', header='Column1,Column2,Column3')
print ('File Saved succesfully!!')

Following is the output obtained −

File Saved succesfully!!

Saving Arrays to Binary Files

Saving arrays to binary files in NumPy is a way to store numerical data in a compact format. Binary files are often used for saving large datasets or for performance reasons, as they are generally faster to read from and write to compared to text files.

NumPy provides np.save() function, np.savez() function and np.savez_compressed() function specifically designed for saving arrays in binary formats.

Using np.save() Function

The np.save() function saves a single NumPy array to a binary file in NumPys native .npy format. This format includes metadata such as the arrays shape and dtype, which allows for loading and manipulation later. Following is the syntax −

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

Where,

  • file: Filename or file object where the array will be saved. The file extension should be .npy.
  • arr: The NumPy array to be saved.
  • allow_pickle: If True, allows saving objects that can be pickled. Default is False.
  • fix_imports: If True, attempts to fix compatibility issues when loading pickled data (for Python 2 to 3).

Example

In this example, we are saving a 2D NumPy array to a binary ".npy" file using np.save() function, which stores the array data efficiently −

import numpy as np

# Create an array
array = np.array([[1, 2, 3], [4, 5, 6]])

# Save the array to a .npy file
np.save('array.npy', array)
print ("File saved!!")

This will produce the following result −

File saved!!

Using np.savez() Function

The np.savez() function saves multiple arrays into a single file with the ".npz" extension. The ".npz" file is a zip archive containing one ".npy" file for each array, which can be accessed by name. Following is the syntax −

numpy.savez(file, *args, **kwargs)

Where,

  • file: Filename or file object where the arrays will be saved. The file extension should be .npz.
  • *args: Arrays to be saved.
  • **kwargs: Keyword arguments specifying names for each array.

Example

In the example below, we are saving multiple NumPy arrays to a compressed ".npz" file using np.savez() function, where "array1" and "array2" are stored with their respective names −

import numpy as np

# Create multiple arrays
array1 = np.array([1, 2, 3])
array2 = np.array([[4, 5, 6], [7, 8, 9]])

# Save the arrays to a .npz file
np.savez('arrays.npz', array1=array1, array2=array2)
print ("File saved!!")

Following is the output of the above code −

File saved!!

Using np.savez_compressed() Function

The np.savez_compressed() function is similar to np.savez() function, but it compresses the arrays to reduce file size. This is useful for storing large datasets more efficiently. Following is the syntax −

numpy.savez_compressed(file, *args, **kwargs)

Where,

  • file: Filename or file object where the arrays will be saved. The file extension should be .npz.
  • *args: Arrays to be saved.
  • **kwargs: Keyword arguments specifying names for each array.

Example

Here, we save multiple NumPy arrays to a compressed ".npz" file using np.savez_compressed() function, which reduces the file size while storing "array1" and "array2" with their respective names −

import numpy as np

# Create multiple arrays
array1 = np.array([1, 2, 3])
array2 = np.array([[4, 5, 6], [7, 8, 9]])

# Save the arrays to a compressed .npz file
np.savez_compressed('arrays_compressed.npz', array1=array1, array2=array2)
print ("File saved!!")

The output obtained is as shown below −

File saved!!
Advertisements