Dremet
Dremet

Reputation: 1038

How to combine two coordinate values in a DataArray (xarray)?

I have an xarray.Dataarray with 4 coordinates: fp, station, run_date, elnu

Dimensions are currently (same order): (1, 2, 3261, 417)

Station has the values "101470" and "108700", want to put these two together to have a dimension of (1, 1, 3261*2, 417) afterwards, I kind of want to reshape them. Problem is, I can't figure out how to do that and how to solve the problem that they would then have the same coordinates (if I would act like they would have the same station).

Maybe I just don't find the right words to search for on google (not native English). Appreciate any help.

Upvotes: 1

Views: 2564

Answers (1)

shoyer
shoyer

Reputation: 9623

The functionality you're looking for is in xarray's .stack() method. Example:

>>> import xarray

>>> import numpy as np

>>> da = xarray.DataArray(np.zeros((1, 2, 3261, 417)), dims=['fp', 'station', 'run_date', 'elnu'])

>>> da
<xarray.DataArray (fp: 1, station: 2, run_date: 3261, elnu: 417)>
array([[[[ 0., ...,  0.],
         ..., 
         [ 0., ...,  0.]],

        [[ 0., ...,  0.],
         ..., 
         [ 0., ...,  0.]]]])
Dimensions without coordinates: fp, station, run_date, elnu

>>> da.stack(station_date=['station', 'run_date'])
<xarray.DataArray (fp: 1, elnu: 417, station_date: 6522)>
array([[[ 0.,  0., ...,  0.,  0.],
        [ 0.,  0., ...,  0.,  0.],
        ..., 
        [ 0.,  0., ...,  0.,  0.],
        [ 0.,  0., ...,  0.,  0.]]])
Coordinates:
  * station_date  (station_date) MultiIndex
  - station       (station_date) int64 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...
  - run_date      (station_date) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ...
Dimensions without coordinates: fp, elnu

Follow up with .transpose() and/or .expand_dims() to reorder dimensions to your desired order.

Upvotes: 3

Related Questions