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

Ensure dtype of reindex result matches dtype of the original DataArray #7917

Merged
merged 2 commits into from Jun 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/whats-new.rst
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
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
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