Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I load a data frame saved in pandas as an HDF5 file in R?

I saved a data frame in pandas in an HDF5 file:

import numpy as np
import pandas as pd
np.random.seed(1)
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'), 
                     index=['Utah', 'Ohio', 'Texas', 'Oregon'])
print('frame: {0}'.format(frame))
store = pd.HDFStore('file.h5')
store['df'] =  frame
store.close()

The frame looks as follows:

frame:                b         d         e
Utah              1.624345 -0.611756 -0.528172
Ohio             -1.072969  0.865408 -2.301539
Texas             1.744812 -0.761207  0.319039
Oregon           -0.249370  1.462108 -2.060141

I am trying to load it in R:

#source("http://bioconductor.org/biocLite.R")
#biocLite("rhdf5")    
library(rhdf5)
frame = h5ls("file.h5")    
frame

However, once loaded in R it looks as follows:

> frame
  group          name       otype dclass   dim
0     /            df   H5I_GROUP             
1   /df         axis0 H5I_DATASET STRING     3
2   /df         axis1 H5I_DATASET STRING     4
3   /df  block0_items H5I_DATASET STRING     3
4   /df block0_values H5I_DATASET  FLOAT 3 x 4
> 

I also tried:

frame2 = h5read("file.h5", '/df')
frame2

However it returns several values but no data frame:

> frame2
$axis0
[1] "b" "d" "e"

$axis1
[1] "Utah"   "Ohio"   "Texas"  "Oregon"

$block0_items
[1] "b" "d" "e"

$block0_values
           [,1]       [,2]       [,3]       [,4]
[1,]  1.6243454 -1.0729686  1.7448118 -0.2493704
[2,] -0.6117564  0.8654076 -0.7612069  1.4621079
[3,] -0.5281718 -2.3015387  0.3190391 -2.0601407

How can I load a data frame saved in pandas as an HDF5 file, in R?

like image 431
Franck Dernoncourt Avatar asked Jul 09 '17 18:07

Franck Dernoncourt


1 Answers

Update This is the recommended approach in the pandas documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#external-compatibility


From https://github.com/pandas-dev/pandas/issues/9636 (thanks John Galt for pointing me to this resource):

Example of HDF5 export for R

import numpy as np
import pandas as pd

np.random.seed(1)
df = pd.DataFrame({"first": np.random.rand(100),
                   "second": np.random.rand(100),
                   "class": np.random.randint(0, 2, (100,))},
                   index=range(100))

print(df.head())

store = pd.HDFStore("transfer.hdf5", "w", complib=str("zlib"), complevel=5)
store.put("dataframe", df, data_columns=df.columns)
store.close()

Output:

   class     first    second
0      0  0.417022  0.326645
1      0  0.720324  0.527058
2      1  0.000114  0.885942
3      1  0.302333  0.357270
4      1  0.146756  0.908535

In R:

# Load values and column names for all datasets from corresponding nodes and
# insert them into one data.frame object.

library(rhdf5)

loadhdf5data <- function(h5File) {

listing <- h5ls(h5File)
# Find all data nodes, values are stored in *_values and corresponding column
# titles in *_items
data_nodes <- grep("_values", listing$name)
name_nodes <- grep("_items", listing$name)

data_paths = paste(listing$group[data_nodes], listing$name[data_nodes], sep = "/")
name_paths = paste(listing$group[name_nodes], listing$name[name_nodes], sep = "/")

columns = list()
for (idx in seq(data_paths)) {
  data <- data.frame(t(h5read(h5File, data_paths[idx])))
  names <- t(h5read(h5File, name_paths[idx]))
  entry <- data.frame(data)
  colnames(entry) <- names
  columns <- append(columns, entry)
}

data <- data.frame(columns)

return(data)
}

Now you can import the DataFrame:

> data = loadhdf5data("transfer.hdf5")
> head(data)
         first    second class
1 0.4170220047 0.3266449     0
2 0.7203244934 0.5270581     0
3 0.0001143748 0.8859421     1
4 0.3023325726 0.3572698     1
5 0.1467558908 0.9085352     1
6 0.0923385948 0.6233601     1
like image 170
Franck Dernoncourt Avatar answered Nov 14 '22 23:11

Franck Dernoncourt