LoginSignup
11
3

More than 3 years have passed since last update.

文字列の配列を HDF5 ファイルに保存する

Last updated at Posted at 2019-09-06

配列、テンソル状の数値データを保存するのに便利は HDF5. 一緒に文字列の配列を保存したい時もある。

Python3 で文字列は UTF8 でエンコーディングされていると仮定する(Python2 は別)dtype=strnp.array では保存できないので注意、

import h5py

a = np.array(['hello', 'world'], 
             dtype=h5py.special_dtype(vlen=str))

with h5py.File('try_string.h5', 'w') as f:
    f['s'] = a

try_string.h5 は任意のファイル名、s は任意のデータ名。

読み込む場合はいつもどおり

with h5py.File('try_string.h5', 'r') as f:
    b = f['s'][:]

type(b), type(b[0])  # => (numpy.ndarray, str)

11
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
3