xarray.broadcast

xarray.broadcast

xarray.broadcast(*args, exclude=None)[source]

Explicitly broadcast any number of DataArray or Dataset objects against one another.

xarray objects automatically broadcast against each other in arithmetic operations, so this function should not be necessary for normal use.

If no change is needed, the input data is returned to the output without being copied.

Parameters
  • *args (DataArray or Dataset) – Arrays to broadcast against each other.

  • exclude (sequence of str, optional) – Dimensions that must not be broadcasted

Returns

broadcast (tuple of DataArray or tuple of Dataset) – The same data as the input arrays, but with additional dimensions inserted so that all data arrays have the same dimensions and shape.

Examples

Broadcast two data arrays against one another to fill out their dimensions:

>>> a = xr.DataArray([1, 2, 3], dims="x")
>>> b = xr.DataArray([5, 6], dims="y")
>>> a
<xarray.DataArray (x: 3)>
array([1, 2, 3])
Dimensions without coordinates: x
>>> b
<xarray.DataArray (y: 2)>
array([5, 6])
Dimensions without coordinates: y
>>> a2, b2 = xr.broadcast(a, b)
>>> a2
<xarray.DataArray (x: 3, y: 2)>
array([[1, 1],
       [2, 2],
       [3, 3]])
Dimensions without coordinates: x, y
>>> b2
<xarray.DataArray (x: 3, y: 2)>
array([[5, 6],
       [5, 6],
       [5, 6]])
Dimensions without coordinates: x, y

Fill out the dimensions of all data variables in a dataset:

>>> ds = xr.Dataset({"a": a, "b": b})
>>> (ds2,) = xr.broadcast(ds)  # use tuple unpacking to extract one dataset
>>> ds2
<xarray.Dataset>
Dimensions:  (x: 3, y: 2)
Dimensions without coordinates: x, y
Data variables:
    a        (x, y) int64 1 1 2 2 3 3
    b        (x, y) int64 5 6 5 6 5 6