Ale*_*Vis 6 hdf5 python-3.x h5py pandas
我正在尝试将Pandas数据框中的数据写入嵌套的hdf5文件中,每个组中包含多个组和数据集。我想将其作为单个文件保存,将来会每天增加。我使用了以下代码,该代码显示了我想要实现的结构
import h5py
import numpy as np
import pandas as pd
file = h5py.File('database.h5','w')
d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
groups = ['A','B','C']
for m in groups:
group = file.create_group(m)
dataset = ['1','2','3']
for n in dataset:
data = df
ds = group.create_dataset(m + n, data.shape)
print ("Dataset dataspace is", ds.shape)
print ("Dataset Numpy datatype is", ds.dtype)
print ("Dataset name is", ds.name)
print ("Dataset is a member of the group", ds.parent)
print ("Dataset was created in the file", ds.file)
print ("Writing data...")
ds[...] = data
print ("Reading data back...")
data_read = ds[...]
print ("Printing data...")
print (data_read)
file.close(
Run Code Online (Sandbox Code Playgroud)
)
这样,便创建了嵌套结构,但丢失了索引和列。我试过了
df.to_hdf('database.h5', ds, table=True, mode='a')
Run Code Online (Sandbox Code Playgroud)
但是没有用,我得到这个错误
AttributeError:“数据集”对象没有属性“拆分”
任何人都可以阐明一下。非常感谢
df.to_hdf()需要一个字符串作为key
参数(第二个参数):
键:字符串
商店中群组的标识符
所以试试这个:
df.to_hdf('database.h5', ds.name, table=True, mode='a')
Run Code Online (Sandbox Code Playgroud)
其中ds.name
应该返回一个字符串(键名):
In [26]: ds.name
Out[26]: '/A1'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9097 次 |
最近记录: |