Skip to content
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

Avoid loading entire dataset by getting the nbytes in an array #7356

Merged
merged 7 commits into from
Dec 12, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ Deprecations
Bug fixes
~~~~~~~~~

- Accessing the property ``.nbytes`` of a DataArray, or Variable no longer
accidentally triggers loading the variable into memory.


Documentation
~~~~~~~~~~~~~
Expand Down
4 changes: 2 additions & 2 deletions xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,8 +403,8 @@ def nbytes(self) -> int:
If the underlying data array does not include ``nbytes``, estimates
the bytes consumed based on the ``size`` and ``dtype``.
"""
if hasattr(self.data, "nbytes"):
return self.data.nbytes
if hasattr(self._data, "nbytes"):
dcherian marked this conversation as resolved.
Show resolved Hide resolved
return self._data.nbytes
else:
return self.size * self.dtype.itemsize

Expand Down
15 changes: 15 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -3259,6 +3259,21 @@ def test_from_series_sparse(self) -> None:
actual_sparse.data = actual_sparse.data.todense()
assert_identical(actual_sparse, actual_dense)

@requires_sparse
def test_sparse_nbytes(self) -> None:
dcherian marked this conversation as resolved.
Show resolved Hide resolved
# https://github.com/pydata/xarray/issues/4842#issue-793245791
df = pd.DataFrame()
df["x"] = np.repeat(np.arange(10), 10)
df["y"] = np.repeat(np.arange(10), 10)
df["time"] = np.tile(pd.date_range("2000-01-01", "2000-03-10", freq="W"), 10)
df["rate"] = 10.0
df = df.set_index(["time", "y", "x"])

sparse_ds = xr.Dataset.from_dataframe(df, sparse=True)
rate = sparse_ds["rate"]
assert rate.nbytes < 8000
assert rate.size * rate.dtype.itemsize == 8000

@requires_sparse
def test_from_multiindex_series_sparse(self) -> None:
# regression test for GH4019
Expand Down