我正在構建模擬軟件,並且需要在HDF5文件的表中寫入(數千個)2D numpy陣列,其中陣列的一個維度是可變的。傳入array
是float32類型;爲了節省磁盤空間,每個數組都以表格的形式存儲,併爲列提供適當的數據類型(因此不使用數組)。當我讀表時,我想檢索一個float32類型的numpy.ndarray,所以我可以爲分析做很好的計算。下面是帶有物種A,B和C加上時間的陣列的示例代碼。讀寫HDF5文件中的numpy陣列
我目前正在閱讀和寫作'作品'的方式,但它非常緩慢。因此,問題是:將array
快速存入table
的適當方式是什麼,並將其再讀回到ndarrays中?我一直在嘗試numpy.recarray,但我無法得到這個工作(輸入錯誤,尺寸錯誤,完全錯誤的數字等)?
代碼:
import tables as pt
import numpy as np
# Variable dimension
var_dim=100
# Example array, rows 0 and 3 should be stored as float32, rows 1 and 2 as uint16
array=(np.random.random((4, var_dim)) * 100).astype(dtype=np.float32)
filename='test.hdf5'
hdf=pt.open_file(filename=filename,mode='w')
group=hdf.create_group(hdf.root,"group")
particle={
'A':pt.Float32Col(),
'B':pt.UInt16Col(),
'C':pt.UInt16Col(),
'time':pt.Float32Col(),
}
dtypes=np.array([
np.float32,
np.uint16,
np.uint16,
np.float32
])
# This is the table to be stored in
table=hdf.create_table(group,'trajectory', description=particle, expectedrows=var_dim)
# My current way of storing
for i, row in enumerate(array.T):
table.append([tuple([t(x) for t, x in zip(dtypes, row)])])
table.flush()
hdf.close()
hdf=pt.open_file(filename=filename,mode='r')
array_table=hdf.root.group._f_iter_nodes().__next__()
# My current way of reading
row_list = []
for i, row in enumerate(array_table.read()):
row_list.append(np.array(list(row)))
#The retreived array
array=np.asarray(row_list).T
# I've tried something with a recarray
rec_array=array_table.read().view(type=np.recarray)
# This gives me errors, or wrong results
rec_array.view(dtype=np.float64)
hdf.close()
的錯誤,我得到:
Traceback (most recent call last):
File "/home/thomas/anaconda3/lib/python3.6/site-packages/numpy/core/records.py", line 475, in __setattr__
ret = object.__setattr__(self, attr, val)
ValueError: new type not compatible with array.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/thomas/Documents/Thesis/SO.py", line 53, in <module>
rec_array.view(dtype=np.float64)
File "/home/thomas/anaconda3/lib/python3.6/site-packages/numpy/core/records.py", line 480, in __setattr__
raise exctype(value)
ValueError: new type not compatible with array.
Closing remaining open files:test.hdf5...done
這可能有助於看到array'的'形狀和D型(從第一個' asarray')。我猜這已經是一個結構化數組。或者'recarray'版本的類似信息。 – hpaulj
使用表格是唯一可能的解決方案嗎?你以後如何訪問你的數據(只有整個二維數組或子集)? – max9111
您的真實數據中是否只有少量列(在您的示例中只有四列)? 你的數據是否可壓縮? 甚至有損壓縮你的可能性? https://computation.llnl.gov/projects/floating-point-compression/zfp-compression-ratio-and-quality – max9111