h5py stores only 0s in datasets

Question:

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

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?

Asked By: user2723984

||

Answers:

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.

Answered By: gspr

Try with

dset[k,l]=matrix[k][l]

instead.

Answered By: 9769953
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.