How to read a specific dataset from an HDF5 file into a NumPy array?
NumPy: I/O Operations Exercise-10 with Solution
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:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
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?
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://w3resource.com/python-exercises/numpy/read-a-specific-dataset-from-an-hdf5-file-into-a-numpy-array.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics