Skip to content

Commit 71defdd

Browse files
authored
Ensure dtype of reindex result matches dtype of the original DataArray (#7917)
* Ensure dtype of reindex result matches dtype of the original DataArray * update what's new
1 parent 276b6bf commit 71defdd

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

doc/whats-new.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ Bug fixes
4646
By `Mattia Almansi <https://github.com/malmans2>`_.
4747
- Don't call ``CachingFileManager.__del__`` on interpreter shutdown (:issue:`7814`, :pull:`7880`).
4848
By `Justus Magin <https://github.com/keewis>`_.
49+
- Ensure dtype of reindex result matches dtype of the original DataArray (:issue:`7299`, :pull:`7917`)
50+
By `Anderson Banihirwe <https://github.com/andersy005>`_.
4951

5052
Documentation
5153
~~~~~~~~~~~~~

xarray/core/dtypes.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,10 @@ def maybe_promote(dtype):
7474
else:
7575
dtype = object
7676
fill_value = np.nan
77-
return np.dtype(dtype), fill_value
77+
78+
dtype = np.dtype(dtype)
79+
fill_value = dtype.type(fill_value)
80+
return dtype, fill_value
7881

7982

8083
NAT_TYPES = {np.datetime64("NaT").dtype, np.timedelta64("NaT").dtype}

xarray/tests/test_dataarray.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1698,6 +1698,19 @@ def test_reindex_str_dtype(self, dtype) -> None:
16981698
assert_identical(expected, actual)
16991699
assert actual.dtype == expected.dtype
17001700

1701+
def test_reindex_empty_array_dtype(self) -> None:
1702+
# Dtype of reindex result should match dtype of the original DataArray.
1703+
# See GH issue #7299
1704+
x = xr.DataArray([], dims=("x",), coords={"x": []}).astype("float32")
1705+
y = x.reindex(x=[1.0, 2.0])
1706+
1707+
assert (
1708+
x.dtype == y.dtype
1709+
), "Dtype of reindexed DataArray should match dtype of the original DataArray"
1710+
assert (
1711+
y.dtype == np.float32
1712+
), "Dtype of reindexed DataArray should remain float32"
1713+
17011714
def test_rename(self) -> None:
17021715
da = xr.DataArray(
17031716
[1, 2, 3], dims="dim", name="name", coords={"coord": ("dim", [5, 6, 7])}

0 commit comments

Comments
 (0)