-
-
Notifications
You must be signed in to change notification settings - Fork 18.5k
REF: Refactor sparse HDF5 read / write #28456
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -28,6 +28,7 @@ | |
is_datetime64tz_dtype, | ||
is_extension_type, | ||
is_list_like, | ||
is_sparse, | ||
is_timedelta64_dtype, | ||
) | ||
from pandas.core.dtypes.missing import array_equivalent | ||
|
@@ -40,8 +41,7 @@ | |
MultiIndex, | ||
PeriodIndex, | ||
Series, | ||
SparseDataFrame, | ||
SparseSeries, | ||
SparseArray, | ||
TimedeltaIndex, | ||
concat, | ||
isna, | ||
|
@@ -173,22 +173,17 @@ class DuplicateWarning(Warning): | |
""" | ||
|
||
# map object types | ||
_TYPE_MAP = { | ||
Series: "series", | ||
SparseSeries: "sparse_series", | ||
DataFrame: "frame", | ||
SparseDataFrame: "sparse_frame", | ||
} | ||
_TYPE_MAP = {Series: "series", DataFrame: "frame"} | ||
|
||
# storer class map | ||
_STORER_MAP = { | ||
"Series": "LegacySeriesFixed", | ||
"DataFrame": "LegacyFrameFixed", | ||
"DataMatrix": "LegacyFrameFixed", | ||
"series": "SeriesFixed", | ||
"sparse_series": "SparseSeriesFixed", | ||
"sparse_series": "SeriesFixed", | ||
"frame": "FrameFixed", | ||
"sparse_frame": "SparseFrameFixed", | ||
"sparse_frame": "FrameFixed", | ||
} | ||
|
||
# table class map | ||
|
@@ -2754,6 +2749,19 @@ def read_array(self, key, start=None, stop=None): | |
elif dtype == "timedelta64": | ||
ret = np.asarray(ret, dtype="m8[ns]") | ||
|
||
if dtype == "Sparse": | ||
if start or stop: | ||
raise NotImplementedError( | ||
"start and/or stop are not supported in fixed Sparse reading" | ||
) | ||
sp_index = self.read_index("{}_sp_index".format(key)) | ||
ret = SparseArray( | ||
ret, | ||
sparse_index=sp_index, | ||
fill_value=self.attrs["{}_fill_value".format(key)], | ||
kind=self.attrs["{}_kind".format(key)], | ||
) | ||
|
||
if transposed: | ||
return ret.T | ||
else: | ||
|
@@ -3004,7 +3012,7 @@ def write_array(self, key, value, items=None): | |
vlarr = self._handle.create_vlarray(self.group, key, _tables().ObjectAtom()) | ||
vlarr.append(value) | ||
else: | ||
if empty_array: | ||
if empty_array and not is_sparse(value): | ||
self.write_array_empty(key, value) | ||
else: | ||
if is_datetime64_dtype(value.dtype): | ||
|
@@ -3021,6 +3029,17 @@ def write_array(self, key, value, items=None): | |
elif is_timedelta64_dtype(value.dtype): | ||
self._handle.create_array(self.group, key, value.view("i8")) | ||
getattr(self.group, key)._v_attrs.value_type = "timedelta64" | ||
elif is_sparse(value): | ||
# TODO: think about EA API for this. | ||
# value._write_hdf5(self) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. is There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Part of the TODO. |
||
self.write_index("{}_sp_index".format(key), value.sp_index) | ||
self._handle.create_array(self.group, key, value.sp_values) | ||
getattr(self.group, key)._v_attrs.value_type = "Sparse" | ||
setattr(self.attrs, "{}_fill_value".format(key), value.fill_value) | ||
setattr(self.attrs, "{}_kind".format(key), value.kind) | ||
self.attributes.extend( | ||
["{}_fill_value".format(key), "{}_kind".format(key)] | ||
) | ||
else: | ||
self._handle.create_array(self.group, key, value) | ||
|
||
|
@@ -3078,83 +3097,6 @@ def write(self, obj, **kwargs): | |
self.attrs.name = obj.name | ||
|
||
|
||
class SparseFixed(GenericFixed): | ||
def validate_read(self, kwargs): | ||
""" | ||
we don't support start, stop kwds in Sparse | ||
""" | ||
kwargs = super().validate_read(kwargs) | ||
if "start" in kwargs or "stop" in kwargs: | ||
raise NotImplementedError( | ||
"start and/or stop are not supported in fixed Sparse reading" | ||
) | ||
return kwargs | ||
|
||
|
||
class SparseSeriesFixed(SparseFixed): | ||
pandas_kind = "sparse_series" | ||
attributes = ["name", "fill_value", "kind"] | ||
|
||
def read(self, **kwargs): | ||
kwargs = self.validate_read(kwargs) | ||
index = self.read_index("index") | ||
sp_values = self.read_array("sp_values") | ||
sp_index = self.read_index("sp_index") | ||
return SparseSeries( | ||
sp_values, | ||
index=index, | ||
sparse_index=sp_index, | ||
kind=self.kind or "block", | ||
fill_value=self.fill_value, | ||
name=self.name, | ||
) | ||
|
||
def write(self, obj, **kwargs): | ||
super().write(obj, **kwargs) | ||
self.write_index("index", obj.index) | ||
self.write_index("sp_index", obj.sp_index) | ||
self.write_array("sp_values", obj.sp_values) | ||
self.attrs.name = obj.name | ||
self.attrs.fill_value = obj.fill_value | ||
self.attrs.kind = obj.kind | ||
|
||
|
||
class SparseFrameFixed(SparseFixed): | ||
pandas_kind = "sparse_frame" | ||
attributes = ["default_kind", "default_fill_value"] | ||
|
||
def read(self, **kwargs): | ||
kwargs = self.validate_read(kwargs) | ||
columns = self.read_index("columns") | ||
sdict = {} | ||
for c in columns: | ||
key = "sparse_series_{columns}".format(columns=c) | ||
s = SparseSeriesFixed(self.parent, getattr(self.group, key)) | ||
s.infer_axes() | ||
sdict[c] = s.read() | ||
return SparseDataFrame( | ||
sdict, | ||
columns=columns, | ||
default_kind=self.default_kind, | ||
default_fill_value=self.default_fill_value, | ||
) | ||
|
||
def write(self, obj, **kwargs): | ||
""" write it as a collection of individual sparse series """ | ||
super().write(obj, **kwargs) | ||
for name, ss in obj.items(): | ||
key = "sparse_series_{name}".format(name=name) | ||
if key not in self.group._v_children: | ||
node = self._handle.create_group(self.group, key) | ||
else: | ||
node = getattr(self.group, key) | ||
s = SparseSeriesFixed(self.parent, node) | ||
s.write(ss) | ||
self.attrs.default_fill_value = obj.default_fill_value | ||
self.attrs.default_kind = obj.default_kind | ||
self.write_index("columns", obj.columns) | ||
|
||
|
||
class BlockManagerFixed(GenericFixed): | ||
attributes = ["ndim", "nblocks"] | ||
is_shape_reversed = False | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems the old "SparseSeriesFixed" used the "sp_values" key to write the sparse values. How does this code work with that? (or why does it not need to read this key specifically?)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let me check (perhaps we don't have test coverage for it)
IIRC, I needed this because
DataFrame.write
eventually calls this on a sparse ExtensionBlock. When I didn't prefix this with thekey
, I got name errors from reading the wrong value (I kept overwritingsp_index
on each column of the dataframe).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm, not tested...
Reading
That's raising on
values
, but it's the same issue. Previously we usedsp_values
, now we use{key}
. Will investigate, and add a failing test.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It might be worth to keep the SparseSeries/SparseFrameFixed classes that you removed (or at least the read part of it), but adjust it to create a Series[sparse] instead of SparseSeries. That seems the easiest to me to handle the legacy hdf5 files that contain such sparse data