w3resource

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

NumPy: I/O Operations Exercise-9 with Solution

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:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: How to save and load multiple NumPy arrays to and from a single binary file?
Next: Write a NumPy program that reads a specific dataset from an HDF5 file into a NumPy array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/save-and-load-a-numpy-array-to-and-from-an-hdf5-file.php