加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – PyTables问题 – 迭代表的子集时的结果不同

发布时间:2020-12-20 11:12:20 所属栏目:Python 来源:网络整理
导读:我是PyTables的新手,我正在考虑使用它处理基于代理的建模仿真生成的数据并存储在HDF5中.我正在使用39 MB的测试文件,并且遇到了一些奇怪的问题.这是表格的布局: /example/agt_coords (Table(2000000,)) '' description := { "agent": Int32Col(shape=(),dflt
我是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=(),pos=2)}
  byteorder := 'little'
  chunkshape := (20000,)

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

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

h5file.root.example.agt_coords
/example/agt_coords (Table(2000000,)
>>> coords = h5file.root.example.agt_coords

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

[x for x in coords[1:100] if x['agent'] == 1]
[(1,25.0,78.0),(1,78.0)]
>>> [x for x in coords if x['agent'] == 1]
[(1000000,(1000000,78.0)]
>>> [x for x in coords.iterrows() if x['agent'] == 1]
[(1000000,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]

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

解决方法

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

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

[x for x in coords if x['agent'] == 1]

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

[x["agent"] for x in coords if x['agent'] == 1]

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

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

[x[:] for x in coords if x['agent'] == 1]

要么

[x.fetch_all_fields() for x in coords if x['agent'] == 1]

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

这是来自PyTables开发人员的a good explanation. In future releases,printing a row accessor object may not simply show the data,but state that it’s a row accessor object.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读