【问题标题】:Storing numpy arrays as PyTables cell element将 numpy 数组存储为 PyTables 单元格元素
【发布时间】:2018-08-09 16:23:57
【问题描述】:

我有 4 个文件,其数据格式如下: 3 个文件包含不同维度的 numpy 数组,例如 20、30 和 25。每个文件中的记录数相同,例如 10000。第四个文件包含 1000浮动(与每个文件中的数组一样多)。 我尝试根据这些文件创建一个具有以下结构的表:

+-----------------------------------------------------------+
| VecsFile #0   | VecsFile #1   | VecsFile #2   | FloatFile |
+-----------------------------------------------------------+
|np.ndarray(20,)|np.ndarray(30,)|np.ndarray(25,)|   0.1     |
+-----------------------------------------------------------+
|np.ndarray(20,)|np.ndarray(30,)|np.ndarray(25,)|   0.2     |
                               ...

我遇到过 PyTables 没有接收 numpy 数组作为单元格数据的有效类型。

代码: 导入表 将 numpy 导入为 np

def create_table_def(n_files):
    table_def = dict()
    for rnum in range(n_files):
        table_def['VecsFile #'+str(rnum)] = tables.Col.from_atom(tables.Float64Atom())
    table_def['FloatFile'] = tables.Col.from_atom(tables.Float64Atom())

    return table_def

r0 = np.load('file0.npy')
r1 = np.load('file1.npy')
r2 = np.load('file2.npy')
s = np.random.rand(*r0.shape)


with tables.open_file('save.hdf', 'w') as saveFile:
    table_def = create_table_def(3)
    table = saveFile.create_table(saveFile.root, 'que_vectors', table_def)
    tablerow = table.row
    for i in range(r0.shape[0]):
        print(r0[i])
        tablerow['VecsFile #0'] = r0[i]
        tablerow['VecsFile #1'] = r1[i]
        tablerow['VecsFile #2'] = r2[i]
        tablerow['FloatFile'] = s[i]
        tablerow.append()
    table.flush()

我得到以下回溯:

    Traceback (most recent call last):
  File "C:/scratch_6.py", line 27, in <module>
    tablerow['VecsFile #0] = r0[i]
  File "tables\tableextension.pyx", line 1591, in tables.tableextension.Row.__setitem__
TypeError: invalid type (<class 'numpy.ndarray'>) for column ``VecsFile #0``

我做错了吗?还是这种方式将这些向量和带有浮点数的列存储为一个文件,而不将所有这些向量附加到一个 numpy 矩阵?我想用它来在将来附加带有向量和一个浮点数的行,对它们进行范围和删除。

【问题讨论】:

  • 我更熟悉HDF5 的h5py 接口,它几乎是一对一的numpy 数组映射。 pytables 更复杂,但我很惊讶它在将数组保存为单元格元素时存在问题。 DataFrame 的单元格是对象 dtype。 h5py 无法保存对象 dtype 数组。
  • 您能否将r0、r1 等作为自己的datasets 保存在h5 文件中?我知道如何使用h5py。
  • 我建议保存一个简单的数据框,并使用h5dump(或其他通用查看器)查看文件以了解 pytables 使用的结构。 h5py 使 HDF5 组像字典一样,数据集像 numpy 数组。
  • 在其他 SO 问题中,人们在将这种数据框保存到 csv 文件时遇到了麻烦。 Pandas 将数组元素转换为字符串,并将其保存为列值。 Pandas 加载无法(轻易)将字符串转换回数组。
  • 我错误地认为您使用的是pandas,尽管pandas 确实使用pytables 来编写HDF5。在任何情况下,我都没有看到这里列出的object dtype:pytables.org/usersguide/datatypes.html。

标签: python arrays numpy pytables


【解决方案1】:
import numpy as np
import tables as tb


class NumpyTable(tb.IsDescription):
    """ define a table with cells of 84 x 84"""
    numpy_cell = tb.Float32Col(shape=(84, 84))


""" open a file and create the table """
fileh = tb.open_file('numpy_cell.h5', mode='w')
group = fileh.create_group(fileh.root, 'group')
filters = tb.Filters(complevel=5, complib='zlib')
np_table = fileh.create_table('/group', 'numpy_table', NumpyTable, "group: NumpyTable",
                              filters=filters)

""" get the last row """
row = np_table.row

""" add a row """
row['numpy_cell'] = np.zeros((84, 84), dtype=np.float32)
row.append()

""" add another row """
row['numpy_cell'] = np.ones((84, 84), dtype=np.float32)
row.append()

""" write to disk and close the file"""
np_table.flush()
fileh.close()

""" check it """
fileh = tb.open_file('numpy_cell.h5', mode='r')
assert np.allclose(
  fileh.root.group.numpy_table[0]['numpy_cell'], 
  np.zeros((84, 84), dtype=np.float32)
)
assert np.allclose(
  fileh.root.group.numpy_table[1]['numpy_cell'], 
  np.ones((84, 84), dtype=np.float32)
)
fileh.close()

【讨论】:

    猜你喜欢
    • 2020-10-17
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    • 2017-10-25
    • 2020-12-13
    相关资源
    最近更新 更多