【问题标题】:Pandas can't read hdf5 file created with h5pyPandas 无法读取使用 h5py 创建的 hdf5 文件
【发布时间】:2016-02-11 23:52:42
【问题描述】:

当我尝试读取使用 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:如果对象不存在也没有传递值,则无法创建存储器

我尝试将密钥集指定为“/zeros”(就像我在读取文件时使用 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'

提前非常感谢, 玛莎

【问题讨论】:

标签: python pandas hdf5 h5py


【解决方案1】:

我在pandas.io 中的pytables 模块上做了一些工作,据我所知,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')

如果您在 HDFView 中打开“test.h5”,您将看到一个路径 /test,其中包含重新创建 DataFrame 所需的 4 个项目。

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

【讨论】:

  • 我想拼接到 Pandas,但看起来我必须保持 h5py 依赖。非常感谢您的回复!
  • 代码不起作用:缺少括号,Series 是一维的,但数据是二维的。可能你想输入pd.DataFrame(np.zeros((3, 5), dtype=np.float32)).to_hdf("test.h5", "test")
猜你喜欢
  • 2022-10-19
  • 2014-12-24
  • 2016-04-08
  • 2015-04-17
  • 2017-04-23
  • 2015-04-09
  • 2016-01-23
  • 1970-01-01
相关资源
最近更新 更多