Skip to content

add join argument to xr.broadcast? #6304

@mathause

Description

@mathause

Is your feature request related to a problem?

xr.broadcast always does an outer join:

def broadcast(*args, exclude=None):

args = align(*args, join="outer", copy=False, exclude=exclude)

This is not how the (default) broadcasting (arithmetic join) works, e.g. the following first does an inner join and then broadcasts:

import xarray as xr

da1 = xr.DataArray([[0, 1, 2]], dims=("y", "x"), coords={"x": [0, 1, 2]})
da2 = xr.DataArray([0, 1, 2, 3, 4], dims="x", coords={"x": [0, 1, 2, 3, 4]})
da1 + da2
<xarray.DataArray (y: 1, x: 3)>
array([[0, 2, 4]])
Coordinates:
  * x        (x) int64 0 1 2
Dimensions without coordinates: y

Describe the solution you'd like

Add a join argument to xr.broadcast. I would propose to leave the default as is

def broadcast(*args, exclude=None, join="outer"):
    args = align(*args, join=join, copy=False, exclude=exclude) 

Describe alternatives you've considered

  • We could make broadcast respect options -> arithmetic_join but that would be a breaking change and I am not sure how the deprecation should/ would be handled...
  • We could leave it as is.

Additional context

  • xr.broadcast should not be used often because this is should happen automatically in most cases
  • in Weighted quantile #6059 I use broadcast because I couldn't get it to work otherwise (maybe there is a better way?). However, the "outer elements" are immediately discarded again - so it's kind of pointless to do an outer join.
import numpy as np
import xarray as xr

da = xr.DataArray(np.arange(6).reshape(3, 2), coords={"dim_0": [0, 1, 2]})
w = xr.DataArray([1, 1, 1, 1, 1, 1], coords={"dim_0": [0, 1, 2, 4, 5, 6]})
da.weighted(w).quantile(0.5)

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