Skip to content

Commit

Permalink
BUG fix +test .sel method gives error with float32 values
Browse files Browse the repository at this point in the history
    .sel method gives error when it is used to select float32 values

    Resolves: #3137
  • Loading branch information
HasanAhmadQ7 authored and HasanAhmadQ7 committed Jul 21, 2019
1 parent 118f4d9 commit 0794f41
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
19 changes: 18 additions & 1 deletion xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1814,8 +1814,9 @@ def sel(self, indexers=None, method=None, tolerance=None, drop=False,
DataArray.sel
"""
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, 'sel')
casted_indexers = self._maybe_cast_floats(indexers)
pos_indexers, new_indexes = remap_label_indexers(
self, indexers=indexers, method=method, tolerance=tolerance)
self, indexers=casted_indexers, method=method, tolerance=tolerance)
result = self.isel(indexers=pos_indexers, drop=drop)
return result._overwrite_indexes(new_indexes)

Expand Down Expand Up @@ -2322,6 +2323,22 @@ def interp_like(self, other, method='linear', assume_sorted=False,
ds = self.reindex(object_coords)
return ds.interp(numeric_coords, method, assume_sorted, kwargs)

# Helper method for sel()
def _maybe_cast_floats(self, indexers):
""" Cast float labels passed to sel() method to the float
types of the corresponding coordinates"""
from .dataarray import DataArray
casted_indexers = indexers.copy()
for k, v in indexers.items():
coords_var = self.coords[k].values
if isinstance(indexers[k], (slice, DataArray, Variable)):
pass
elif (isinstance(coords_var, np.ndarray) and
coords_var.dtype.kind == 'f'):
casting_type = getattr(coords_var.dtype, "type")
casted_indexers[k] = casting_type(indexers[k])
return casted_indexers

# Helper methods for rename()
def _rename_vars(self, name_dict, dims_dict):
variables = OrderedDict()
Expand Down
10 changes: 10 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -817,6 +817,16 @@ def test_sel_dataarray_datetime(self):
result = array.sel(delta=slice(array.delta[0], array.delta[-1]))
assert_equal(result, array)

def test_sel_float32(self):
float_values = [0., 0.111, 0.222, 0.333]
coord_values = np.asarray(float_values, dtype='float32')
data_values = np.arange(4)
array = DataArray(data_values, [('float32_coord', coord_values)])
expected = DataArray(data_values[1:3], [('float32_coord',
coord_values[1:3])])
actual = array.sel(float32_coord=float_values[1:3])
assert_equal(expected, actual)

def test_sel_no_index(self):
array = DataArray(np.arange(10), dims='x')
assert_identical(array[0], array.sel(x=0))
Expand Down

0 comments on commit 0794f41

Please sign in to comment.