Skip to content

String handling when using .sel (method='nearest') to find a location #10276

Open
@Breeze-Hu

Description

@Breeze-Hu

Is your feature request related to a problem?

Hi!

Below I have provided a scenario that may not be code that minimally reproduces the problem, but had to be done to more clearly describe the meaning of the behaviour.

import xarray as xr
import numpy as np
import pandas as pd
 
# example data
time = pd.date_range("2000-01-01", "2001-12-31", freq="D")
time = time[~((time.month == 2) & (time.day == 29))] 

lon = np.linspace(100, 110, 5)
lat = np.linspace(30, 35, 4)
data = np.random.rand(len(time), len(lon), len(lat))

da = xr.DataArray(
    data,
    coords={"time": time, "lon": lon, "lat": lat},
    dims=["time", "lon", "lat"],
    name="pr"
)

# Split based on year and month-days
da1 = da.assign_coords(year = da.time.dt.year, monthday = da.time.dt.strftime("%m-%d")).groupby(['year', 'monthday']).first()

# Make a selection on the data of da1:
da1.sel(year = 2000, monthday = '03-24', lon = 105, lat = 30) # It's ok

# Problems arose once the method was used for the most recently search:
da1.sel(year = 2000, monthday = '03-24', lon = 105, lat = 30, method='nearest') 

Describe the solution you'd like

I'm guessing the problem is related to its type: monthday (monthday) object

# I know there are many solutions. For example:
da1.sel(year = 2000, monthday = '03-24').sel(lon = 105, lat = 30, method='nearest')

For greater clarity and simplicity in the use of indexes, is it possible to add judgement to the function?

  • Firstly make a judgement on the type of the sel, it is this type that can't be used with method = “nearest”, such as strings, etc., and if it doesn't match exactly break the operation and point it out in the error message.
  • After the types that can't be “nearest” have been processed, then the subsequent selections are used.

Describe alternatives you've considered

No response

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions