33import warnings
44
55import numpy as np
6+ import pandas as pd
67from pandas import HDFStore
78
89from larray .core .array import Array
1213from larray .core .metadata import Metadata
1314from larray .util .misc import LHDFStore
1415from larray .inout .session import register_file_handler
15- from larray .inout .common import FileHandler
16+ from larray .inout .common import FileHandler , _supported_typenames , _supported_scalars_types
1617from larray .inout .pandas import df_asarray
1718from larray .example import get_example_filepath
1819
1920
21+ # for backward compatibility (larray < 0.29) but any object read from an hdf file should have
22+ # an attribute 'type'
23+ def _get_type_from_attrs (attrs ):
24+ return attrs .type if 'type' in attrs else 'Array'
25+
26+
2027def read_hdf (filepath_or_buffer , key , fill_value = nan , na = nan , sort_rows = False , sort_columns = False ,
2128 name = None , ** kwargs ):
22- r"""Reads an axis or group or array named key from a HDF5 file in filepath (path+name)
29+ r"""Reads a scalar or an axis or group or array named key from a HDF5 file in filepath (path+name)
2330
2431 Parameters
2532 ----------
2633 filepath_or_buffer : str or pandas.HDFStore
2734 Path and name where the HDF5 file is stored or a HDFStore object.
2835 key : str or Group
29- Name of the array.
36+ Name of the scalar or axis or group or array.
3037 fill_value : scalar or Array, optional
3138 Value used to fill cells corresponding to label combinations which are not present in the input.
3239 Defaults to NaN.
@@ -70,11 +77,14 @@ def read_hdf(filepath_or_buffer, key, fill_value=nan, na=nan, sort_rows=False, s
7077 key = _translate_group_key_hdf (key )
7178 res = None
7279 with LHDFStore (filepath_or_buffer ) as store :
73- pd_obj = store .get (key )
80+ try :
81+ pd_obj = store .get (key )
82+ except KeyError :
83+ filepath = filepath_or_buffer if isinstance (filepath_or_buffer , HDFStore ) else store .filename
84+ raise KeyError ('No item with name {} has been found in file {}' .format (key , filepath ))
7485 attrs = store .get_storer (key ).attrs
7586 writer = attrs .writer if 'writer' in attrs else None
76- # for backward compatibility but any object read from an hdf file should have an attribute 'type'
77- _type = attrs .type if 'type' in attrs else 'Array'
87+ _type = _get_type_from_attrs (attrs )
7888 _meta = attrs .metadata if 'metadata' in attrs else None
7989 if _type == 'Array' :
8090 # cartesian product is not necessary if the array was written by LArray
@@ -110,6 +120,10 @@ def read_hdf(filepath_or_buffer, key, fill_value=nan, na=nan, sort_rows=False, s
110120 key = np .char .decode (key , 'utf-8' )
111121 axis = read_hdf (filepath_or_buffer , attrs ['axis_key' ])
112122 res = LGroup (key = key , name = name , axis = axis )
123+ elif _type in _supported_typenames :
124+ res = pd_obj .values
125+ assert len (res ) == 1
126+ res = res [0 ]
113127 return res
114128
115129
@@ -126,36 +140,37 @@ def _open_for_write(self):
126140
127141 def list_items (self ):
128142 keys = [key .strip ('/' ) for key in self .handle .keys ()]
143+ items = [(key , _get_type_from_attrs (self .handle .get_storer (key ).attrs )) for key in keys if '/' not in key ]
144+ # ---- for backward compatibility (LArray < 0.33) ----
129145 # axes
130- items = [(key .split ('/' )[- 1 ], 'Axis ' ) for key in keys if '__axes__' in key ]
146+ items + = [(key .split ('/' )[- 1 ], 'Axis_Backward_Comp ' ) for key in keys if '__axes__' in key ]
131147 # groups
132- items += [(key .split ('/' )[- 1 ], 'Group' ) for key in keys if '__groups__' in key ]
133- # arrays
134- items += [(key , 'Array' ) for key in keys if '/' not in key ]
148+ items += [(key .split ('/' )[- 1 ], 'Group_Backward_Comp' ) for key in keys if '__groups__' in key ]
135149 return items
136150
137- def _read_item (self , key , type , * args , ** kwargs ):
138- if type == 'Array' :
151+ def _read_item (self , key , typename , * args , ** kwargs ):
152+ if typename in _supported_typenames :
139153 hdf_key = '/' + key
140- elif type == 'Axis' :
154+ # ---- for backward compatibility (LArray < 0.33) ----
155+ elif typename == 'Axis_Backward_Comp' :
141156 hdf_key = '__axes__/' + key
142- elif type == 'Group ' :
157+ elif typename == 'Group_Backward_Comp ' :
143158 hdf_key = '__groups__/' + key
144159 else :
145160 raise TypeError ()
146161 return read_hdf (self .handle , hdf_key , * args , ** kwargs )
147162
148163 def _dump_item (self , key , value , * args , ** kwargs ):
149- if isinstance (value , Array ):
150- hdf_key = '/' + key
151- value .to_hdf (self .handle , hdf_key , * args , ** kwargs )
152- elif isinstance (value , Axis ):
153- hdf_key = '__axes__/' + key
164+ hdf_key = '/' + key
165+ if isinstance (value , (Array , Axis )):
154166 value .to_hdf (self .handle , hdf_key , * args , ** kwargs )
155167 elif isinstance (value , Group ):
156- hdf_key = '__groups__/' + key
157- hdf_axis_key = '__axes__/' + value .axis .name
168+ hdf_axis_key = '/' + value .axis .name
158169 value .to_hdf (self .handle , hdf_key , hdf_axis_key , * args , ** kwargs )
170+ elif isinstance (value , _supported_scalars_types ):
171+ s = pd .Series (data = value )
172+ self .handle .put (hdf_key , s )
173+ self .handle .get_storer (hdf_key ).attrs .type = type (value ).__name__
159174 else :
160175 raise TypeError ()
161176
0 commit comments