w3resource

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


9. HDF5 File Write/Read

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to write an array to an HDF5 file and then read it back, ensuring the dataset attributes match.
  • Write a Numpy program to export a multidimensional array to HDF5 and then perform a partial read on a subset of the dataset.
  • Write a Numpy program to save an array to HDF5 and then use slicing on the HDF5 dataset to retrieve specific rows.
  • Write a Numpy program to store an array in an HDF5 file and then compare the read array with the original using hash checks.

Go to:


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.

Python-Numpy Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.