Skip to content

Commit

Permalink
Ensure dtype of reindex result matches dtype of the original DataArray (
Browse files Browse the repository at this point in the history
pydata#7917)

* Ensure dtype of reindex result matches dtype of the original DataArray

* update what's new
  • Loading branch information
andersy005 authored Jun 16, 2023
1 parent 276b6bf commit 71defdd
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ Bug fixes
By `Mattia Almansi <https://github.com/malmans2>`_.
- Don't call ``CachingFileManager.__del__`` on interpreter shutdown (:issue:`7814`, :pull:`7880`).
By `Justus Magin <https://github.com/keewis>`_.
- Ensure dtype of reindex result matches dtype of the original DataArray (:issue:`7299`, :pull:`7917`)
By `Anderson Banihirwe <https://github.com/andersy005>`_.

Documentation
~~~~~~~~~~~~~
Expand Down
5 changes: 4 additions & 1 deletion xarray/core/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,10 @@ def maybe_promote(dtype):
else:
dtype = object
fill_value = np.nan
return np.dtype(dtype), fill_value

dtype = np.dtype(dtype)
fill_value = dtype.type(fill_value)
return dtype, fill_value


NAT_TYPES = {np.datetime64("NaT").dtype, np.timedelta64("NaT").dtype}
Expand Down
13 changes: 13 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -1698,6 +1698,19 @@ def test_reindex_str_dtype(self, dtype) -> None:
assert_identical(expected, actual)
assert actual.dtype == expected.dtype

def test_reindex_empty_array_dtype(self) -> None:
# Dtype of reindex result should match dtype of the original DataArray.
# See GH issue #7299
x = xr.DataArray([], dims=("x",), coords={"x": []}).astype("float32")
y = x.reindex(x=[1.0, 2.0])

assert (
x.dtype == y.dtype
), "Dtype of reindexed DataArray should match dtype of the original DataArray"
assert (
y.dtype == np.float32
), "Dtype of reindexed DataArray should remain float32"

def test_rename(self) -> None:
da = xr.DataArray(
[1, 2, 3], dims="dim", name="name", coords={"coord": ("dim", [5, 6, 7])}
Expand Down

0 comments on commit 71defdd

Please sign in to comment.