2009-12-18 87 views
3

我是PyTables的新手,我正在使用它來處理從基於代理的建模模擬生成的數據並存儲在HDF5中。我正在使用一個39 MB的測試文件,並且正在經歷一些奇怪的事情。下面是表的佈局:PyTables問題 - 在迭代表子集時產生不同結果

/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,) 

這裏是我如何在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 

現在,這裏的事情變得怪異。

[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] 

我不明白爲什麼值搞砸了,當我遍歷整個表,而不是當我把整個行集的一小部分。我確信這是我使用圖書館的一個錯誤,所以在這個問題上的任何幫助將非常感激。

回答

7

遍歷Table對象時,這是混亂的一個非常普遍的問題,

當你遍歷一個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 explanationIn future releases, printing a row accessor object may not simply show the data, but state that it's a row accessor object

+0

感謝您對意外行爲的非常詳細的解釋。我真的希望教程(例如http://www.pytables.org/moin/HintsForSQLUsers,http://www.pytables.org/docs/manual/ch03.html(請參閱3.1.6) )記錄了什麼你解釋一下 – I82Much 2009-12-21 17:14:48