Skip to content

Instantly share code, notes, and snippets.

@Ionizing
Created July 30, 2024 18:16
Show Gist options
  • Save Ionizing/e8afeb9f47b537bbc2a0afdd31711036 to your computer and use it in GitHub Desktop.
Save Ionizing/e8afeb9f47b537bbc2a0afdd31711036 to your computer and use it in GitHub Desktop.
Write numpy array as scalar to a HDF5 file.
#!/usr/bin/env python3
import h5py
import numpy as np
with h5py.File("test.h5", "w") as f:
# A is in SIMPLE DataSpace
f["A"] = np.array([1, 2])
# B is in SCALAR DataSpace
ds = f.create_dataset(name="B", shape=(), dtype=np.dtype(("<u8", (2,))))
data = np.array([1, 2])
space = h5py.h5s.ALL
tid = h5py.h5t.py_create(np.dtype(("<u8", (2,))))
ds.id.write(space, space, data, mtype=tid)
@Ionizing
Copy link
Author

Example output:

HDF5 "test.h5" {
GROUP "/" {
   DATASET "A" {
      DATATYPE  H5T_STD_I64LE
      DATASPACE  SIMPLE { ( 2 ) / ( 2 ) }
      DATA {
      (0): 1, 2
      }
   }
   DATASET "B" {
      DATATYPE  H5T_ARRAY { [2] H5T_STD_U64LE }
      DATASPACE  SCALAR
      DATA {
      (0): [ 1, 2 ]
      }
   }
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment