PyTables create_array无法保存numpy数组

问题描述

为什么下面的代码给出了

“ TypeError:数组对象当前无法处理void,unicode或对象数组”

Python 3.8.2,表3.6.1,numpy 1.19.1

import numpy as np
import tables as tb
TYPE = np.dtype([
    ('d','f4')
])
with tb.open_file(r'c:\temp\file.h5',mode="a") as h5file:
    h5file.create_group(h5file.root,'grp')
    arr = np.array([(1.1)],dtype=TYPE)
    h5file.create_array('/grp',str('arr'),arr)

解决方法

File.create_array()适用于同类dtypes(所有int或所有floats等)。 PyTables使用不同的对象来保存混合的类型。您需要改用File.create_table()。请参阅下面的修改代码(仅更改了最后一行)。

TYPE = np.dtype([ ('d','f4') ])
with tb.open_file(r'c:\temp\file.h5',mode="a") as h5file:
    h5file.create_group(h5file.root,'grp')
    arr = np.array([(1.1)],dtype=TYPE)
    h5file.create_table('/grp',str('arr'),arr)

注意:如果使用以前工作中的现有mode='a'文件运行,则temp.h5会出错。这是由于与第一次创建的组/grp发生冲突。