Reshaping and reorganizing data

These methods allow you to reorganize

Reordering dimensions

To reorder dimensions on a DataArray or across all variableson a Dataset, use transpose():

  1. In [1]: ds = xr.Dataset({'foo': (('x', 'y', 'z'), [[[42]]]), 'bar': (('y', 'z'), [[24]])})
  2.  
  3. In [2]: ds.transpose('y', 'z', 'x')
  4. Out[2]:
  5. <xarray.Dataset>
  6. Dimensions: (x: 1, y: 1, z: 1)
  7. Dimensions without coordinates: x, y, z
  8. Data variables:
  9. foo (y, z, x) int64 42
  10. bar (y, z) int64 24
  11.  
  12. In [3]: ds.transpose() # reverses all dimensions
  13. Out[3]:
  14. <xarray.Dataset>
  15. Dimensions: (x: 1, y: 1, z: 1)
  16. Dimensions without coordinates: x, y, z
  17. Data variables:
  18. foo (z, y, x) int64 42
  19. bar (z, y) int64 24

Expand and squeeze dimensions

To expand a DataArray or allvariables on a Dataset along a new dimension,use expand_dims()

  1. In [4]: expanded = ds.expand_dims('w')
  2.  
  3. In [5]: expanded
  4. Out[5]:
  5. <xarray.Dataset>
  6. Dimensions: (w: 1, x: 1, y: 1, z: 1)
  7. Dimensions without coordinates: w, x, y, z
  8. Data variables:
  9. foo (w, x, y, z) int64 42
  10. bar (w, y, z) int64 24

This method attaches a new dimension with size 1 to all data variables.

To remove such a size-1 dimension from the DataArrayor Dataset,use squeeze()

  1. In [6]: expanded.squeeze('w')
  2. Out[6]:
  3. <xarray.Dataset>
  4. Dimensions: (x: 1, y: 1, z: 1)
  5. Dimensions without coordinates: x, y, z
  6. Data variables:
  7. foo (x, y, z) int64 42
  8. bar (y, z) int64 24

Converting between datasets and arrays

To convert from a Dataset to a DataArray, use to_array():

  1. In [7]: arr = ds.to_array()
  2.  
  3. In [8]: arr
  4. Out[8]:
  5. <xarray.DataArray (variable: 2, x: 1, y: 1, z: 1)>
  6. array([[[[42]]],
  7.  
  8.  
  9. [[[24]]]])
  10. Coordinates:
  11. * variable (variable) <U3 'foo' 'bar'
  12. Dimensions without coordinates: x, y, z

This method broadcasts all data variables in the dataset against each other,then concatenates them along a new dimension into a new array while preservingcoordinates.

To convert back from a DataArray to a Dataset, useto_dataset():

  1. In [9]: arr.to_dataset(dim='variable')
  2. Out[9]:
  3. <xarray.Dataset>
  4. Dimensions: (x: 1, y: 1, z: 1)
  5. Dimensions without coordinates: x, y, z
  6. Data variables:
  7. foo (x, y, z) int64 42
  8. bar (x, y, z) int64 24

The broadcasting behavior of to_array means that the resulting arrayincludes the union of data variable dimensions:

  1. In [10]: ds2 = xr.Dataset({'a': 0, 'b': ('x', [3, 4, 5])})
  2.  
  3. # the input dataset has 4 elements
  4. In [11]: ds2
  5. Out[11]:
  6. <xarray.Dataset>
  7. Dimensions: (x: 3)
  8. Dimensions without coordinates: x
  9. Data variables:
  10. a int64 0
  11. b (x) int64 3 4 5
  12.  
  13. # the resulting array has 6 elements
  14. In [12]: ds2.to_array()
  15. Out[12]:
  16. <xarray.DataArray (variable: 2, x: 3)>
  17. array([[0, 0, 0],
  18. [3, 4, 5]])
  19. Coordinates:
  20. * variable (variable) <U1 'a' 'b'
  21. Dimensions without coordinates: x

Otherwise, the result could not be represented as an orthogonal array.

If you use to_dataset without supplying the dim argument, the DataArray will be converted into a Dataset of one variable:

  1. In [13]: arr.to_dataset(name='combined')
  2. Out[13]:
  3. <xarray.Dataset>
  4. Dimensions: (variable: 2, x: 1, y: 1, z: 1)
  5. Coordinates:
  6. * variable (variable) <U3 'foo' 'bar'
  7. Dimensions without coordinates: x, y, z
  8. Data variables:
  9. combined (variable, x, y, z) int64 42 24

Stack and unstack

As part of xarray’s nascent support for pandas.MultiIndex, we haveimplemented stack() andunstack() method, for combining or splitting dimensions:

  1. In [14]: array = xr.DataArray(np.random.randn(2, 3),
  2. ....: coords=[('x', ['a', 'b']), ('y', [0, 1, 2])])
  3. ....:
  4.  
  5. In [15]: stacked = array.stack(z=('x', 'y'))
  6.  
  7. In [16]: stacked
  8. Out[16]:
  9. <xarray.DataArray (z: 6)>
  10. array([ 0.469112, -0.282863, -1.509059, -1.135632, 1.212112, -0.173215])
  11. Coordinates:
  12. * z (z) MultiIndex
  13. - x (z) object 'a' 'a' 'a' 'b' 'b' 'b'
  14. - y (z) int64 0 1 2 0 1 2
  15.  
  16. In [17]: stacked.unstack('z')
  17. Out[17]:
  18. <xarray.DataArray (x: 2, y: 3)>
  19. array([[ 0.469112, -0.282863, -1.509059],
  20. [-1.135632, 1.212112, -0.173215]])
  21. Coordinates:
  22. * x (x) object 'a' 'b'
  23. * y (y) int64 0 1 2

These methods are modeled on the pandas.DataFrame methods of thesame name, although in xarray they always create new dimensions rather thanadding to the existing index or columns.

Like DataFrame.unstack, xarray’s unstackalways succeeds, even if the multi-index being unstacked does not contain allpossible levels. Missing levels are filled in with NaN in the resulting object:

  1. In [18]: stacked2 = stacked[::2]
  2.  
  3. In [19]: stacked2
  4. Out[19]:
  5. <xarray.DataArray (z: 3)>
  6. array([ 0.469112, -1.509059, 1.212112])
  7. Coordinates:
  8. * z (z) MultiIndex
  9. - x (z) object 'a' 'a' 'b'
  10. - y (z) int64 0 2 1
  11.  
  12. In [20]: stacked2.unstack('z')
  13. Out[20]:
  14. <xarray.DataArray (x: 2, y: 3)>
  15. array([[ 0.469112, nan, -1.509059],
  16. [ nan, 1.212112, nan]])
  17. Coordinates:
  18. * x (x) object 'a' 'b'
  19. * y (y) int64 0 1 2

However, xarray’s stack has an important difference from pandas: unlikepandas, it does not automatically drop missing values. Compare:

  1. In [21]: array = xr.DataArray([[np.nan, 1], [2, 3]], dims=['x', 'y'])
  2.  
  3. In [22]: array.stack(z=('x', 'y'))
  4. Out[22]:
  5. <xarray.DataArray (z: 4)>
  6. array([nan, 1., 2., 3.])
  7. Coordinates:
  8. * z (z) MultiIndex
  9. - x (z) int64 0 0 1 1
  10. - y (z) int64 0 1 0 1
  11.  
  12. In [23]: array.to_pandas().stack()
  13. Out[23]:
  14. x y
  15. 0 1 1.0
  16. 1 0 2.0
  17. 1 3.0
  18. dtype: float64

We departed from pandas’s behavior here because predictable shapes for newarray dimensions is necessary for Parallel computing with Dask.

Stacking different variables together

These stacking and unstacking operations are particularly useful for reshapingxarray objects for use in machine learning packages, such as scikit-learn, that usually require two-dimensional numpyarrays as inputs. For datasets with only one variable, we only need stackand unstack, but combining multiple variables in axarray.Dataset is more complicated. If the variables in the datasethave matching numbers of dimensions, we can callto_array() and then stack along the the new coordinate.But to_array() will broadcast the dataarrays together,which will effectively tile the lower dimensional variable along the missingdimensions. The method xarray.Dataset.to_stacked_array() allowscombining variables of differing dimensions without this wasteful copying whilexarray.DataArray.to_unstacked_dataset() reverses this operation.Just as with xarray.Dataset.stack() the stacked coordinate isrepresented by a pandas.MultiIndex object. These methods are usedlike this:

In this example, stacked is a two dimensional array that we can easily pass to a scikit-learn or another genericnumerical method.

Note

Unlike with stack, in to_stacked_array, the user specifies the dimensions they do not want stacked.For a machine learning task, these unstacked dimensions can be interpreted as the dimensions over which samples aredrawn, whereas the stacked coordinates are the features. Naturally, all variables should possess these samplingdimensions.

Set and reset index

Complementary to stack / unstack, xarray’s .set_index, .reset_index and.reorder_levels allow easy manipulation of DataArray or Datasetmulti-indexes without modifying the data and its dimensions.

You can create a multi-index from several 1-dimensional variables and/orcoordinates using set_index():

  1. In [24]: da = xr.DataArray(np.random.rand(4),
  2. ....: coords={'band': ('x', ['a', 'a', 'b', 'b']),
  3. ....: 'wavenumber': ('x', np.linspace(200, 400, 4))},
  4. ....: dims='x')
  5. ....:
  6.  
  7. In [25]: da
  8. Out[25]:
  9. <xarray.DataArray (x: 4)>
  10. array([0.123102, 0.543026, 0.373012, 0.447997])
  11. Coordinates:
  12. band (x) <U1 'a' 'a' 'b' 'b'
  13. wavenumber (x) float64 200.0 266.7 333.3 400.0
  14. Dimensions without coordinates: x
  15.  
  16. In [26]: mda = da.set_index(x=['band', 'wavenumber'])
  17.  
  18. In [27]: mda
  19. Out[27]:
  20. <xarray.DataArray (x: 4)>
  21. array([0.123102, 0.543026, 0.373012, 0.447997])
  22. Coordinates:
  23. * x (x) MultiIndex
  24. - band (x) object 'a' 'a' 'b' 'b'
  25. - wavenumber (x) float64 200.0 266.7 333.3 400.0

These coordinates can now be used for indexing, e.g.,

  1. In [28]: mda.sel(band='a')
  2. Out[28]:
  3. <xarray.DataArray (wavenumber: 2)>
  4. array([0.123102, 0.543026])
  5. Coordinates:
  6. * wavenumber (wavenumber) float64 200.0 266.7

Conversely, you can use reset_index()to extract multi-index levels as coordinates (this is mainly usefulfor serialization):

  1. In [29]: mda.reset_index('x')
  2. Out[29]:
  3. <xarray.DataArray (x: 4)>
  4. array([0.123102, 0.543026, 0.373012, 0.447997])
  5. Coordinates:
  6. band (x) object 'a' 'a' 'b' 'b'
  7. wavenumber (x) float64 200.0 266.7 333.3 400.0
  8. Dimensions without coordinates: x

reorder_levels() allows changing the orderof multi-index levels:

  1. In [30]: mda.reorder_levels(x=['wavenumber', 'band'])
  2. Out[30]:
  3. <xarray.DataArray (x: 4)>
  4. array([0.123102, 0.543026, 0.373012, 0.447997])
  5. Coordinates:
  6. * x (x) MultiIndex
  7. - wavenumber (x) float64 200.0 266.7 333.3 400.0
  8. - band (x) object 'a' 'a' 'b' 'b'

As of xarray v0.9 coordinate labels for each dimension are optional.You can also use .set_index / .reset_index to add / removelabels for one or several dimensions:

  1. In [31]: array = xr.DataArray([1, 2, 3], dims='x')
  2.  
  3. In [32]: array
  4. Out[32]:
  5. <xarray.DataArray (x: 3)>
  6. array([1, 2, 3])
  7. Dimensions without coordinates: x
  8.  
  9. In [33]: array['c'] = ('x', ['a', 'b', 'c'])
  10.  
  11. In [34]: array.set_index(x='c')
  12. Out[34]:
  13. <xarray.DataArray (x: 3)>
  14. array([1, 2, 3])
  15. Coordinates:
  16. * x (x) object 'a' 'b' 'c'
  17.  
  18. In [35]: array = array.set_index(x='c')
  19.  
  20. In [36]: array = array.reset_index('x', drop=True)

Shift and roll

To adjust coordinate labels, you can use the shift() androll() methods:

  1. In [37]: array = xr.DataArray([1, 2, 3, 4], dims='x')
  2.  
  3. In [38]: array.shift(x=2)
  4. Out[38]:
  5. <xarray.DataArray (x: 4)>
  6. array([nan, nan, 1., 2.])
  7. Dimensions without coordinates: x
  8.  
  9. In [39]: array.roll(x=2, roll_coords=True)
  10. Out[39]:
  11. <xarray.DataArray (x: 4)>
  12. array([3, 4, 1, 2])
  13. Dimensions without coordinates: x

Sort

One may sort a DataArray/Dataset via sortby() andsortby(). The input can be an individual or list of1D DataArray objects:

  1. In [40]: ds = xr.Dataset({'A': (('x', 'y'), [[1, 2], [3, 4]]),
  2. ....: 'B': (('x', 'y'), [[5, 6], [7, 8]])},
  3. ....: coords={'x': ['b', 'a'], 'y': [1, 0]})
  4. ....:
  5.  
  6. In [41]: dax = xr.DataArray([100, 99], [('x', [0, 1])])
  7.  
  8. In [42]: day = xr.DataArray([90, 80], [('y', [0, 1])])
  9.  
  10. In [43]: ds.sortby([day, dax])
  11. Out[43]:
  12. <xarray.Dataset>
  13. Dimensions: (x: 2, y: 2)
  14. Coordinates:
  15. * x (x) object 'b' 'a'
  16. * y (y) int64 1 0
  17. Data variables:
  18. A (x, y) int64 1 2 3 4
  19. B (x, y) int64 5 6 7 8

As a shortcut, you can refer to existing coordinates by name:

  1. In [44]: ds.sortby('x')
  2. Out[44]:
  3. <xarray.Dataset>
  4. Dimensions: (x: 2, y: 2)
  5. Coordinates:
  6. * x (x) object 'a' 'b'
  7. * y (y) int64 1 0
  8. Data variables:
  9. A (x, y) int64 3 4 1 2
  10. B (x, y) int64 7 8 5 6
  11.  
  12. In [45]: ds.sortby(['y', 'x'])
  13. Out[45]:
  14. <xarray.Dataset>
  15. Dimensions: (x: 2, y: 2)
  16. Coordinates:
  17. * x (x) object 'a' 'b'
  18. * y (y) int64 0 1
  19. Data variables:
  20. A (x, y) int64 4 3 2 1
  21. B (x, y) int64 8 7 6 5
  22.  
  23. In [46]: ds.sortby(['y', 'x'], ascending=False)
  24. Out[46]:
  25. <xarray.Dataset>
  26. Dimensions: (x: 2, y: 2)
  27. Coordinates:
  28. * x (x) object 'b' 'a'
  29. * y (y) int64 1 0
  30. Data variables:
  31. A (x, y) int64 1 2 3 4
  32. B (x, y) int64 5 6 7 8