【发布时间】:2020-10-28 03:03:34
【问题描述】:
我有一个包含 15 个数组的 HDF5 文件,仅此而已。通常我会使用 SQL 查询这些信息,但数据库已关闭,我有一个 HDF5 文件和 PyTables。我可以在 PyTables 上找到的唯一查询输出“行”而不是列中的特定元素是在表上完成的,而不是数组。
目前,我一直在自己的 h5 文件中从头开始创建表,单独填充每一行,并每隔一段时间刷新一次。这需要很长时间,因为有 2900 万行。这是我用来创建表格的代码:
#Defining Table Structure
table_description = {
'Column1':tables.FloatCol(),
'Column2':tables.FloatCol(),
'Column3':tables.FloatCol(),
....
'Column15':tables.FloatCol()}
#Opening the HDF5 file
hdf5_file = h5py.File('File Path','r')
#Pulling out the arrays (the future columns)
Column1_array = np.array(hdf5_file.get('Column1'))
Column2_array = np.array(hdf5_file.get('Column2'))
Column3_array = np.array(hdf5_file.get('Column3'))
...
Column15_array = np.array(hdf5_file.get('Column15'))
#Creating a New H5 file
new_file = tables.open_file('new_table.h5','w')
#Creating a New Table in the File
tbl = new_file.create_table('/','Big_Table',table_description)
i = 0
row = tbl.row #A row pointer
while i < 29069765: #Since I know the length of the columns, I'm able to just index.
row['Column1'] = Column1_array[i] #Filling each column in a row.
row['Column2'] = Column2_array[i] #I have pulled each column out of the HDF5 file,
row['Column3'] = Column3_array[i] #using h5py.
...
row['Column15'] = Column15_array[i]
row.append() #Adding the row to the table
i += 1
if math.fmod(i,100) == 0: #Every 100 rows, I flush the table and the file
tbl.flush()
h5file.flush()
new_file.close()
我还没有开始查询它的过程,但我打算在Big_Table上使用Table.where()函数。
有没有更快的方法将所有这些列数组组合到一个表中并在其上运行多参数查询?
【问题讨论】:
-
如何将这些
columns数组放入pandas数据帧中,然后从那里写入表格?每列都应作为pandas系列工作,您也可以将column_stack数组转换为一个二维数组。一次填充一个数字肯定看起来很慢:row['Column1'] = Column1_array[i]Column1_array是一个数组,这样处理时效果最好。这样的迭代比使用 python 列表慢! -
我没想过要尝试熊猫!它一直很慢,大约需要一个半小时才能填满表格。我会考虑使用熊猫。
-
用行迭代器填充是最慢的方法。由于您为每一列创建了一个数组,因此只需将每一列的数组写入
Big_Table中的匹配字段即可。
标签: python arrays hdf5 h5py pytables