PyTables问题 - 迭代表的子集时会产生不同的结果

I82*_*uch 3 python numpy pytables

我是PyTables的新手,我正在考虑使用它处理基于代理的建模仿真生成的数据并存储在HDF5中.我正在使用39 MB的测试文件,并且遇到了一些奇怪的问题.这是表格的布局:

    /example/agt_coords (Table(2000000,)) ''
  description := {
  "agent": Int32Col(shape=(), dflt=0, pos=0),
  "x": Float64Col(shape=(), dflt=0.0, pos=1),
  "y": Float64Col(shape=(), dflt=0.0, pos=2)}
  byteorder := 'little'
  chunkshape := (20000,)
Run Code Online (Sandbox Code Playgroud)

这是我在Python中访问它的方式:

from tables import *
>>> h5file = openFile("alternate_hose_test.h5", "a")

h5file.root.example.agt_coords
/example/agt_coords (Table(2000000,)) ''
  description := {
  "agent": Int32Col(shape=(), dflt=0, pos=0),
  "x": Float64Col(shape=(), dflt=0.0, pos=1),
  "y": Float64Col(shape=(), dflt=0.0, pos=2)}
  byteorder := 'little'
  chunkshape := (20000,)
>>> coords = h5file.root.example.agt_coords
Run Code Online (Sandbox Code Playgroud)

现在这里的事情变得奇怪了.

[x for x in coords[1:100] if x['agent'] == 1]
[(1, 25.0, 78.0), (1, 25.0, 78.0)]
>>> [x for x in coords if x['agent'] == 1]
[(1000000, 25.0, 78.0), (1000000, 25.0, 78.0)]
>>> [x for x in coords.iterrows() if x['agent'] == 1]
[(1000000, 25.0, 78.0), (1000000, 25.0, 78.0)]
>>> [x['agent'] for x in coords[1:100] if x['agent'] == 1]
[1, 1]
>>> [x['agent'] for x in coords if x['agent'] == 1]
[1, 1]
Run Code Online (Sandbox Code Playgroud)

我不明白为什么当我遍历整个表时,这些值被搞砸了,但是当我占用整个行集的一小部分时却没有.我确定这是我如何使用该库的错误,所以在这个问题上的任何帮助将非常感激.

AFo*_*lia 7

迭代Table对象时,这是一个非常常见的混淆点,

迭代Table所获得的项目类型时,不是项目中的数据,而是当前行中表格的访问者.所以

[x for x in coords if x['agent'] == 1]
Run Code Online (Sandbox Code Playgroud)

您创建一个行访问器列表,它们都指向表的"当前"行,即最后一行.但是,当你这样做

[x["agent"] for x in coords if x['agent'] == 1]
Run Code Online (Sandbox Code Playgroud)

在构建列表时使用访问器.

通过在每次迭代时使用访问器,在构建列表时获取所需的所有数据的解决方案.有两种选择

[x[:] for x in coords if x['agent'] == 1]
Run Code Online (Sandbox Code Playgroud)

要么

[x.fetch_all_fields() for x in coords if x['agent'] == 1]
Run Code Online (Sandbox Code Playgroud)

前者构建了一个元组列表.后者返回NumPy void对象.IIRC,第二个更快,但前者可能对你更有意义.

这是PyTables开发人员的一个很好的解释. 在将来的版本中,打印行访问器对象可能不仅仅显示数据,而是声明它是行访问器对象.