w3resource

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


10. Specific Dataset from HDF5

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to open an HDF5 file and read a specific dataset by its path, then verify the dimensions.
  • Write a Numpy program to read multiple datasets from an HDF5 file and then merge them into a single array.
  • Write a Numpy program to extract a dataset from an HDF5 file and then perform statistical analysis on the data.
  • Write a Numpy program to read a dataset from HDF5 and apply a transformation function before comparing with the original.

Go to:


Previous: How to save and load a NumPy array to and from an HDF5 file?
Next: How to save and load a large NumPy array to and from a compressed .npz file?

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.