我正在尝试将 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()
这样嵌套结构被创建,但它丢失了索引和列。我试过了df.to_hdf('database.h5', ds, table=True, mode='a')
但没有用,我收到这个错误AttributeError: 'Dataset' object has no attribute 'split'
任何人都可以请说明一下。非常感谢
最佳答案
df.to_hdf()期望字符串为 key
参数(第二个参数):
key : string
identifier for the group in the store
所以试试这个:
df.to_hdf('database.h5', ds.name, table=True, mode='a')
哪里ds.name
应该返回一个字符串(键名):In [26]: ds.name
Out[26]: '/A1'
关于python-3.x - 如何将 Pandas 数据帧写入 HDF5 数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47165911/