Skip to content

Allow interpolating along singleton dimensions #10747

@gronniger

Description

@gronniger

Is your feature request related to a problem?

Currently, interpolating along a singleton dimension will always yield nan values.
E.g.

import xarray as xr

da = xr.DataArray([[0, 1]], coords={'a': [1.], 'b': [2., 3.]}).interp(a=1., b=2.5)

raises a warning

***\site-packages\scipy\interpolate\_interpolate.py:479: RuntimeWarning: invalid value encountered in divide
  slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None]

and returns array with correct shape, but all values nan:

<xarray.DataArray ()> Size: 8B
array(nan)
Coordinates:
    a        float64 8B 1.0
    b        float64 8B 2.5

Having only a single coordinate, interpolation is not well defined, of course.
But giving the exact coordinate value in interp(), should simply do a sel() along this dimension before interpolation.
That seems unambiguous and would be what users may reasonably expect.

This is particularly used, when interpolating with coordinates determined by computed dicts, like:

kwargs = dict(a=1., b=2.5)   # from external input
da.interp(**kwargs)

Describe the solution you'd like

import xarray as xr

da = xr.DataArray([[0, 1]], coords={'a': [1.], 'b': [2., 3.]}).interp(a=1., b=2.5)

should yield

<xarray.DataArray ()> Size: 8B
array(0.5)
Coordinates:
    a        float64 8B 1.0
    b        float64 8B 2.5

Describe alternatives you've considered

Of course, singleton dimensions can be detected and special-cases manually:

import xarray as xr

kwargs = dict(a=1., b=2.5)   # from external input
da = xr.DataArray([[0, 1]], coords={'a': [1.], 'b': [2., 3.]})
sel_kwargs = {k: v for k, v in kwargs.items() if da.sizes[k] == 1}
interp_kwargs = {k: v for k, v in kwargs.items() if k not in sel_kwargs.keys()}
da.sel(**sel_kwargs).interp(**interp_kwargs)

This yields the desired behaviour, but feels very clumsy.

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