我有一个像这样创建的多维 Pandas 数据框:
import numpy as np
import pandas as pd
iterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two']]
mindex = pd.MultiIndex.from_product(iterables, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(8, 4), index=mindex)
store = pd.HDFStore("df.h5")
store["df"] = df
store.close()
我想将属性添加到存储在 HDFStore 中的 df。我怎样才能做到这一点?好像没有documentation关于属性,用于存储 df 的组与 h5py 模块中的 HDF5 组不是同一类型:
type(list(store.groups())[0])
Out[24]: tables.group.Group
似乎是 pytables 组,它只有这个涉及其他类型属性的私有(private)成员函数:
__setattr__(self, name, value)
| Set a Python attribute called name with the given value.
我想要的是简单地存储一堆具有多维索引的数据帧,这些索引以结构化方式由属性“标记”,以便我可以比较它们并根据这些属性对它们进行子选择。
基本上,HDF5 的用途是来自 pandas 的 + multidim DataFrame。
有类似this one的问题,它处理与 pandas 以外的其他阅读器一起读取 HDF5 文件,但它们都具有带有一维索引的 DataFrame,这使得简单地转储 numpy ndarrays 并另外存储索引变得容易。
请您参考如下方法:
到目前为止我还没有得到任何答案,这是我使用 pandas 和 h5py 模块设法做到的:pandas用于存储和读取多维DataFrame,h5py用于存储和读取HDF5组的属性:
import numpy as np
import pandas as pd
import h5py
# Create a random multidim DataFrame
iterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two']]
mindex = pd.MultiIndex.from_product(iterables, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(8, 4), index=mindex)
pdStore = pd.HDFStore("df.h5")
h5pyFile = h5py.File("df.h5")
# Dumping the data and storing the attributes
pdStore["df"] = df
h5pyFile["/df"].attrs["number"] = 1
# Reading the data conditionally based on stored attributes.
dfg = h5pyFile["/df"]
readDf = pd.DataFrame()
if dfg.attrs["number"] == 1:
readDf = pdStore["/df"]
print (readDf - df)
h5pyFile.close()
pdStore.close()
我仍然不知道让 h5py 和 pandas 同时处理 .h5 文件是否有任何问题。
