H5PY如何存储多个不同维度的2D数组

2024-09-28 13:15:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python将收集到的数据(来自计算机模拟)组织到hdf5文件中。 我测量了某个空间区域内所有原子的位置和速度[x,y,z,vx,vy,vz]。当然,原子的数量随着时间的推移而变化。在

一个最小的例子如下:

[
[ [x1,y1,z1,vx1,vy1,vz1], [x2,y2,z2,vx2,vy2,vz2] ],
[ [x1,y1,z1,vx1,vy1,vz1], [x2,y2,z2,vx2,vy2,vz2], [x3,y3,z3,vx3,vy3,vz3] ] 
]

(2个时间步, 第一步:2个原子, 第二时间步:3个原子)

我的想法是在Python中创建一个hdf5数据集来存储所有信息。在每个时间步,它应该存储所有原子的所有位置/速度的二维数组,即

^{pr2}$

我想这个想法很清楚。但是,我很难定义数组长度可变的数据集的正确数据类型。在

我的代码如下:

import numpy as np
import h5py

file = h5py.File ('file.h5','w')

columnNo = 6    
rowtype = np.dtype("%sfloat32" % columnNo)
dt = h5py.special_dtype( vlen=np.dtype(rowtype) )

dataset = file.create_dataset("dset", (2,), dtype=dt)

print dataset.value

testarray = np.array([[1.,2.,3.,2.,3.,4.],[1.,2.,3.,2.,3.,4.]])
print testarray

dataset[0] = testarray
print dataset[0]

然而,这是行不通的。当我运行脚本时,我得到错误消息“AttributeError:'float'object has no attribute'dtype'。” 看来我定义的数据类型是错误的。在

有人知道应该如何正确定义它吗?在

非常感谢, 斯文


Tags: 数据定义np时间dataset速度filehdf5
2条回答

谢谢你的快速回答。这帮了大忙。在

如果我现在只需将数据集的数据类型更改为

dtype = dt,

我得到了我想要的。在

这里,Python代码(为了完整性):

^{pr2}$

以及相应的输出读数

('rowtype', dtype([('f0', '<f4', (6,))]))
('dt', dtype('O'))
[ array([([1.0, 1.0, 1.0, 1.0, 1.0, 1.0],),
       ([1.0, 1.0, 1.0, 1.0, 1.0, 1.0],), ([1.0, 1.0, 1.0, 1.0, 1.0, 1.0],)], 
      dtype=[('f0', '<f4', (6,))])
 array([([1.0, 2.0, 3.0, 2.0, 3.0, 4.0],), ([2.0, 3.0, 4.0, 1.0, 2.0, 3.0],)], 
      dtype=[('f0', '<f4', (6,))])]
[([1.0, 1.0, 1.0, 1.0, 1.0, 1.0],) ([1.0, 1.0, 1.0, 1.0, 1.0, 1.0],)
 ([1.0, 1.0, 1.0, 1.0, 1.0, 1.0],)]
[([1.0, 2.0, 3.0, 2.0, 3.0, 4.0],) ([2.0, 3.0, 4.0, 1.0, 2.0, 3.0],)]

为了正确起见:我最初代码中的问题是我的rowtype数据结构定义错误,对吧?在

最好的, 斯文

您的案例中的错误被隐藏了,但是很明显,在尝试将testarray分配给dataset时会发生:

Traceback (most recent call last):
  File "stack41465480.py", line 26, in <module>
    dataset[0] = testarray
  File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper (/build/h5py-GhwtGD/h5py-2.6.0/h5py/_objects.c:2577)
 ...
  File "h5py/_conv.pyx", line 712, in h5py._conv.ndarray2vlen (/build/h5py-GhwtGD/h5py-2.6.0/h5py/_conv.c:6171)
AttributeError: 'float' object has no attribute 'dtype'

使用cd4{cd6}来构造 ^{pr2}$

生产

1316:~/mypy$ python3 stack41465480.py 
rowtype [('f0', '<f4', (6,))]
dt object
value
([0.0, 0.0, 0.0, 0.0, 0.0, 0.0],)
array([([1.0, 1.0, 1.0, 1.0, 1.0, 1.0],), ([1.0, 1.0, 1.0, 1.0, 1.0, 1.0],)], 
      dtype=[('f0', '<f4', (6,))])
[([1.0, 1.0, 1.0, 1.0, 1.0, 1.0],) ([0.0, 0.0, 0.0, 0.0, 0.0, 0.0],)]
array([([1.0, 2.0, 3.0, 2.0, 3.0, 4.0],), ([2.0, 3.0, 4.0, 1.0, 2.0, 3.0],)], 
      dtype=[('f0', '<f4', (6,))])
[([1.0, 1.0, 1.0, 1.0, 1.0, 1.0],) ([2.0, 3.0, 4.0, 1.0, 2.0, 3.0],)]
[[ 1.  1.  1.  1.  1.  1.]
 [ 2.  3.  4.  1.  2.  3.]]

相关问题 更多 >

    热门问题