DataArray.expand_dims(dim=None, axis=None, create_index_for_new_dim=True, **dim_kwargs)[source]#

Return a new object with an additional axis (or axes) inserted at the corresponding position in the array shape. The new object is a view into the underlying array, not a copy.

If dim is already a scalar coordinate, it will be promoted to a 1D coordinate consisting of a single value.

The automatic creation of indexes to back new 1D coordinate variables controlled by the create_index_for_new_dim kwarg.

  • dim (Hashable, sequence of Hashable, dict, or None, optional) – Dimensions to include on the new variable. If provided as str or sequence of str, then dimensions are inserted with length 1. If provided as a dict, then the keys are the new dimensions and the values are either integers (giving the length of the new dimensions) or sequence/ndarray (giving the coordinates of the new dimensions).

  • axis (int, sequence of int, or None, default: None) – Axis position(s) where new axis is to be inserted (position(s) on the result array). If a sequence of integers is passed, multiple axes are inserted. In this case, dim arguments should be same length list. If axis=None is passed, all the axes will be inserted to the start of the result array.

  • create_index_for_new_dim (bool, default: True) – Whether to create new PandasIndex objects when the object being expanded contains scalar variables with names in dim.

  • **dim_kwargs (int or sequence or ndarray) – The keywords are arbitrary dimensions being inserted and the values are either the lengths of the new dims (if int is given), or their coordinates. Note, this is an alternative to passing a dict to the dim kwarg and will only be used if dim is None.


expanded (DataArray) – This object, but with additional dimension(s).


>>> da = xr.DataArray(np.arange(5), dims=("x"))
>>> da
<xarray.DataArray (x: 5)> Size: 40B
array([0, 1, 2, 3, 4])
Dimensions without coordinates: x

Add new dimension of length 2:

>>> da.expand_dims(dim={"y": 2})
<xarray.DataArray (y: 2, x: 5)> Size: 80B
array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]])
Dimensions without coordinates: y, x
>>> da.expand_dims(dim={"y": 2}, axis=1)
<xarray.DataArray (x: 5, y: 2)> Size: 80B
array([[0, 0],
       [1, 1],
       [2, 2],
       [3, 3],
       [4, 4]])
Dimensions without coordinates: x, y

Add a new dimension with coordinates from array:

>>> da.expand_dims(dim={"y": np.arange(5)}, axis=0)
<xarray.DataArray (y: 5, x: 5)> Size: 200B
array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]])
  * y        (y) int64 40B 0 1 2 3 4
Dimensions without coordinates: x