Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a Pandas Dataframe into a HDF5 dataset

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

like image 903
AleVis Avatar asked Nov 07 '17 19:11

AleVis


2 Answers

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'
like image 158
MaxU - stop WAR against UA Avatar answered Nov 13 '22 10:11

MaxU - stop WAR against UA


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:]
like image 44
AleVis Avatar answered Nov 13 '22 12:11

AleVis