Pandas无法读取用h5py创建的hdf5文件。

问题描述 投票:6回答:1

当我试图读取我用h5py创建的HDF5格式文件时,我得到了pandas错误。我想知道我是不是做错了什么?

import h5py
import numpy as np
import pandas as pd
h5_file = h5py.File('test.h5', 'w')
h5_file.create_dataset('zeros', data=np.zeros(shape=(3, 5)), dtype='f')
h5_file.close()
pd_file = pd.read_hdf('test.h5', 'zeros')

给出一个错误:TypeError: cannot create a storer if the object is not existing nor a value are passed.

我试着将key设置为'0'(就像我在读取文件时用h5py做的那样),但没有成功。

如果我使用 pandas.HDFStore 来读取它,我得到的是一个空的存储。

store = pd.HDFStore('test.h5')
>>> store
<class 'pandas.io.pytables.HDFStore'>
File path: test.h5
Empty

我用h5py读回刚创建的文件没有任何问题。

h5_back = h5py.File('test.h5', 'r')
h5_back['/zeros']
<HDF5 dataset "zeros": shape (3, 5), type "<f4">

使用这些版本。

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

pd.__version__
'0.16.2'
h5py.__version__
'2.5.0'

非常感谢,Masha

python matlab pandas hdf5 h5py
1个回答
15
投票

我已经在 pytables 模组 pandas.io 据我所知,pandas与HDF文件的交互仅限于pandas能够理解的特定结构。 要想知道这些结构是什么样子的,你可以尝试以下方法

import pandas as pd
import numpy as np
pd.Series(np.zeros((3,5),dtype=np.float32).to_hdf('test.h5','test')

如果你打开'test.h5'在 HDFView,你会看到一个路径 /test 与4个项目,需要重新创建。DataFrame.

HDFView of test.h5

所以我认为你唯一的选择是直接读取NumPy数组,然后将这些数组转换为Pandas对象。

© www.soinside.com 2019 - 2024. All rights reserved.