Skip to main content
 首页 » 编程设计

python之如何为 hdf5 正确使用 Pandas 迭代器

2025年05月04日11jpfss

我有一个 HDF5 文件,我只是想以 block 的形式读取数据并输出到 mySQL 表。

使用 pandas v. 0.12.0 代码看起来像,

iter = store.select('data',iterator=True, chunksize=5000) 
for data in iter: 
    # write the data out  

但我得到一个异常(exception):

for data in iter: 
  File "d:\python27\lib\site-packages\pandas\io\pytables.py", line 969, in __iter__ 
  v = self.func(current, stop) 
  File "d:\python27\lib\site-packages\pandas\io\pytables.py", line 451, in func 
    return s.read(where=where, start=_start, stop=_stop, columns=columns, **kwargs) 
  File "d:\python27\lib\site-packages\pandas\io\pytables.py", line 3175, in read 
 
    mgr = BlockManager([block], [cols_, index_]) 
  File "d:\python27\lib\site-packages\pandas\core\internals.py", line 1001, in __init__ 
    self._verify_integrity() 
  File "d:\python27\lib\site-packages\pandas\core\internals.py", line 1239, in _verify_integrity 
construction_error(tot_items,block.values.shape[1:],self.axes) 
  File "d:\python27\lib\site-packages\pandas\core\internals.py", line 2216, in construction_error 
tuple(map(int, [len(ax) for ax in axes])))) 
ValueError: Shape of passed values is (1, 5000), indices imply (1, 3751044) 

我不明白错误在说什么,ValueError: Shape of passed values is (1, 5000), indices imply (1, 3751044)。而且我不知道如何让它开心。

我认为 chunksize=5000 值会告诉 pandas 读取 5000 行 block 中的数据,但显然它不喜欢这样进行迭代。 select(chunksize=XXXX) 的正确用法是什么?

请您参考如下方法:

我讨厌回答我自己的问题,但为了帮助以后可能遇到同样问题的其他人,我在这里。

正如 Jeff 提到的,磁盘上的 PyTables HDF5 文件中没有 pandas 元数据。所以我做了什么:

h5file = tables.open_file(file, mode="r") 
signal_data = h5file.root.signal_data 
data_frame = pd.DataFrame.from_records(signal_data) 

现在我可以根据需要在 Pandas 中操作 data_frame。

感谢Jeff寻求帮助。