How to write a Pandas Dataframe into a HDF5 dataset

社会主义新天地 提交于 2020-01-02 04:24:45

问题


I'm trying to write data from a Pandas dataframe into a nested hdf5 file, with multiple groups and datasets within each group. I'd like to keep it as a single file which will grow in the future on a daily basis. I've had a go with the following code, which shows the structure of what I'd like to achieve

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(

)

This way the nested structure is created but it loses the index and columns. I've tried the

df.to_hdf('database.h5', ds, table=True, mode='a')

but didn't work, I get this error

AttributeError: 'Dataset' object has no attribute 'split'

Can anyone shed some light please. Many thanks


回答1:


df.to_hdf() expects a string as a key parameter (second parameter):

key : string

identifier for the group in the store

so try this:

df.to_hdf('database.h5', ds.name, table=True, mode='a')

where ds.name should return you a string (key name):

In [26]: ds.name
Out[26]: '/A1'



回答2:


I thought to have a go with pandas\pytables and the HDFStore class instead of h5py. So I tried the following

import numpy as np
import pandas as pd

db = pd.HDFStore('Database.h5')

index = pd.date_range('1/1/2000', periods=8)

df = pd.DataFrame(np.random.randn(8, 3), index=index, columns=['Col1', 'Col2', 'Col3'])

groups = ['A','B','C']     

i = 1    

for m in groups:

    subgroups = ['d','e','f']

    for n in subgroups:

        db.put(m + '/' + n, df, format = 'table', data_columns = True)

It works, 9 groups (groups instead of datasets in pyatbles instead fo h5py?) created from A/d to C/f. Columns and indexes preserved and can do the dataframe operations I need. Still wondering though whether this is an efficient way to retrieve data from a specific group which will become huge in the the future i.e. operations like

db['A/d'].Col1[4:]


来源:https://stackoverflow.com/questions/47165911/how-to-write-a-pandas-dataframe-into-a-hdf5-dataset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!