简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM