是否有一种方法来扩展一个PyTables数组在第二次元?



我有一个2D数组,它可以增长到比我能够适应内存更大的大小,所以我试图使用Pytables将其存储在h5文件中。行数是事先已知的,但每行的长度是未知的,并且行与行之间是可变的。经过一番研究,我认为这样做是可行的,我可以将可扩展维度设置为第二大维度。

filename = os.path.join(tempfile.mkdtemp(), 'example.h5')
h5_file = open_file(filename, mode="w", title="Example Extendable Array")
h5_group = h5_file.create_group("/", "example_on_dim_2")
e_array = h5_file.create_earray(h5_group, "example", Int32Atom(shape=()), (100, 0)) # Assume num of rows is 100
# Add some item to index 2
print(e_array[2]) # should print an empty array
e_array[2] = np.append(e_array[2], 5) # add the value 5 to row 2
print(e_array[2]) # should print [5], currently printing empty array

我不确定是否有可能以这种方式添加元素(我可能误解了earray的工作方式),但任何帮助都会非常感激!

你很接近…但是对一些争论和行为有一个小小的误解。当你用shape=(100,0)创建EArray时,你没有任何数据…只是一个对象,指定有100行,可以添加列。此外,您需要使用e_array.append()来添加数据,而不是np.append()。另外,如果要创建一个非常大的数组,请考虑定义expectedrows=参数,以便随着数组的增长提高性能。

看一下这段代码。

import tables as tb
import numpy as np
filename = 'example.h5'
with tb.File(filename, mode="w", title="Example Extendable Array") as h5_file :
h5_group = h5_file.create_group("/", "example_on_dim_2")
# Assume num of rows is 100
#e_array = h5_file.create_earray(h5_group, "example", Int32Atom(shape=()), (100, 0)) 
e_array = h5_file.create_earray(h5_group, "example", atom=tb.IntAtom(), shape=(100, 0)) 
print (e_array.shape)
e_array.append(np.arange(100,dtype=int).reshape(100,1)) # append a column of values
print (e_array.shape)
print(e_array[2]) # prints [2]

下面是一个演示如何创建varray的示例(可变长度)。它类似于上面的EArray示例,并遵循Pytables文档中的示例(链接在上面的注释中)。然而,尽管varray支持变长行,它没有向现有行添加项的机制(AFAIK)。

import tables as tb
import numpy as np
filename = 'example_vlarray.h5'
with tb.File(filename, mode="w", title="Example Variable Length Array") as h5_file :
h5_group = h5_file.create_group("/", "vl_example")
vlarray = h5_file.create_vlarray(h5_group, "example", tb.IntAtom(), "ragged array of ints",) 
# Append some (variable length) rows:
vlarray.append(np.array([0]))
vlarray.append(np.array([1, 2]))
vlarray.append([3, 4, 5])
vlarray.append([6, 7, 8, 9])
# Now, read it through an iterator:
print('-->', vlarray.title)
for x in vlarray:
print('%s[%d]--> %s' % (vlarray.name, vlarray.nrow, x))

最新更新