Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

h5py stores only 0s in datasets

I’m trying to store some values in an h5py file, but every time I try to store a matrix in a dataset, all the matrix elements are replaced by 0s. Here’s an example

I create the file like this:

output_file=h5py.File('output_file', 'w')

dset=output_file.create_dataset('dset', (3,3))

for k in range(3):
    for l in range(3):
        dset[k][l]=1.

I then read the file and try to print the output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

file=h5py.File('output_file', 'r')

print(file['dset'][:])

the output is

[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

all the 1s have been turned into 0s. What am I doing wrong?

>Solution :

This is explicitly covered in the manual. When you do dset[k], you create a temporary array. It is this array’s l‘th element that you set when you do dset[k][l] = 1.0. That temporary array is not the h5py dataset that you want to be referring to – you aren’t touching the latter at all.

In short: index with dset[k, l] instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading