w3resource

How to save and load a NumPy array to and from an HDF5 file?


Write a NumPy array to an HDF5 file and then read it back into a NumPy array.

Sample Solution:

Python Code:

import numpy as np
import h5py

# Create a NumPy array
data_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Define the path to the HDF5 file
hdf5_file_path = 'data.h5'

# Save the NumPy array to an HDF5 file
with h5py.File(hdf5_file_path, 'w') as hdf5_file:
    hdf5_file.create_dataset('dataset', data=data_array)

# Read the NumPy array from the HDF5 file
with h5py.File(hdf5_file_path, 'r') as hdf5_file:
    loaded_array = hdf5_file['dataset'][:]

# Print the original and loaded NumPy arrays
print("Original NumPy Array:")
print(data_array)

print("\nLoaded NumPy Array from HDF5 File:")
print(loaded_array)

Output:

Original NumPy Array:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Loaded NumPy Array from HDF5 File:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Explanation:

  • Import NumPy and h5py Libraries: Import the NumPy and h5py libraries to handle arrays and HDF5 file operations.
  • Create NumPy Array: Define a NumPy array with some example data.
  • Define HDF5 File Path: Specify the path where the HDF5 file will be saved.
  • Save Array to HDF5 File: Open the HDF5 file in write mode using h5py.File(). Create a dataset within the file using create_dataset() and save the NumPy array to this dataset.
  • Read Array from HDF5 File: Open the HDF5 file in read mode using h5py.File(). Read the dataset back into a NumPy array.
  • Finally print the original NumPy array and the loaded array to verify that the data was saved and read correctly.

Python-Numpy Code Editor: