w3resource

How to read a specific dataset from an HDF5 file into a NumPy array?


Write a NumPy program that reads a specific dataset from an HDF5 file into a NumPy array.

Sample Solution:

Python Code:

import numpy as np
import h5py

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

# Read the specific dataset from the HDF5 file into a NumPy array
with h5py.File(hdf5_file_path, 'r') as hdf5_file:
    dataset_name = 'dataset'  # Specify the dataset name
    data_array = hdf5_file[dataset_name][:]

# Print the NumPy array
print(data_array)

Output:

[[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.
  • Define HDF5 File Path: Specify the path to the HDF5 file containing the dataset.
  • Read Specific Dataset: Open the HDF5 file in read mode using h5py.File(). Specify the name of the dataset you want to read and load it into a NumPy array.
  • Print NumPy Array: Output the resulting NumPy array to verify that the dataset was read correctly from the HDF5 file.

Python-Numpy Code Editor: