关于python:PyTables批处理获取和更新

PyTables batch get and update

我每天都有使用PyTables创建的HDF5文件作为库存数据。我想获取一组行,将其作为数组处理,然后使用PyTables将其写回到磁盘(更新行)。我想不出一种干净的方法。您能否让我知道实现此目标的最佳方法是什么?

我的资料:

1
2
3
4
5
6
7
8
Symbol, date, price, var1, var2
abcd, 1, 2.5, 12, 12.5
abcd, 2, 2.6, 11, 10.2
abcd, 3, 2.45, 11, 10.3
defg, 1,12.34, 19.1, 18.1
defg, 2, 11.90, 19.5, 18.2
defg, 3, 11.75, 21, 20.9
defg, 4, 11.74, 22.2, 21.4

我想将与每个符号对应的行读取为数组,进行一些处理并更新字段var1和var2。我事先知道所有符号,因此可以循环浏览它们。我尝试过这样的事情:

1
rows_array = [row.fetch_all_fields() for row in table.where('Symbol =="abcd"')]

我想将rows_array传递给另一个函数,该函数将计算var1和var2的值并为每个记录更新它。请注意,var1,var2就像移动平均值一样,因此我将无法在迭代器中计算它们,因此需要将整个行集作为一个数组。

在使用rows_array计算所需的内容之后,我不确定如何将其写回到数据中,即,使用新的计算值更新行。更新整个表时,我使用以下方法:

1
 table.cols.var1[:] = calc_something(rows_array)

但是,当我只想更新表的一部分时,我并不是最好的方法。我想我可以重新运行" where"条件,然后根据我的计算来更新每一行,但这似乎浪费时间重新扫描表。

感谢您的建议...

谢谢,
-e


如果我了解得很好,那么下一个应该做你想做的:

1
2
3
4
5
condition = 'Symbol =="abcd"'
indices = table.getWhereList(condition)  # get indices
rows_array = table[indices]  # get values
new_rows = compute(rows_array)   # compute new values
table[indices] = new_rows  # update the indices with new values

希望这可以帮助