使用Pytables将一张表的所有行追加到另一张表中

1 投票
2 回答
1297 浏览
提问于 2025-04-18 14:17

我们来看一个例子:

import tables
import numpy as np

# Two Example Tables
hfile = tables.open_file('myfile.h5', 'a')
data1 = np.ones((3, 2))
data1.dtype = [('a', float), ('b', float)]
data2 = np.zeros((3, 2))
data2.dtype = [('a', float), ('b', float)]

table1 = hfile.create_table(where='/', name='table1', obj=data1)
table2 = hfile.create_table(where='/', name='table2', obj=data2)

# Appending
table1.append(table2.read())
table2.remove()

hfile.flush()
hfile.close()

有没有更好的方法来处理这个磁盘上的操作?

一种解决方案是逐行遍历:

for r in table2.iterrows():
    table1.append([r[:]])

后者看起来太笨重,而前者在添加之前会把整个第二个表格都加载到内存中。我更希望能做一些像这样的事情:

table2.append_where(dstTable=table1)

但这个函数只在有条件的情况下工作,所以我需要一个总是返回真的条件,才能获取整个表格。肯定还有更好的方法。

2 个回答

0

我为PyTables创建了一个拉取请求,让某个条件变成可选的,这是应@jtorca的要求。因为有一位维护者表示支持,所以这个请求很可能会被接受,并在未来的PyTables版本中加入。

1

我觉得用 append_where() 这个函数,条件简单到像 'True' 这样的写法,可能是最好的解决办法。

撰写回答