magon
magon

Reputation: 55

Xarray - Changing Data Variables into Dimensions

I am working with a lot of temperature data which has been measured at different longitudes and latitudes and I can open it from a NetCDF file like this.

<xarray.Dataset>
Dimensions:            (altitude: 801, measurement_number: 3180)
Coordinates:
   * altitude           (altitude) float64 0.0 100.0 200.0 300.0 400.0 500.0 ...
Dimensions without coordinates: measurement_number
Data variables:
    temperature        (measurement_number, altitude) float32 ...
    longitude          (measurement_number) float64 ...
    latitude           (measurement_number) float64 ...

To evaluate the results more conveniently I want to change the variables "longitude" and "latitude" into dimensions or coordinates like this.

<xarray.Dataset>
Dimensions:            (altitude: 801, measurement_number: 3180, longitude: 36, latitude: 18)
Coordinates:
   * altitude           (altitude) float64 0.0 100.0 200.0 300.0 400.0 500.0 ...
   * longitude          (longitude) float64 -180, -170, -160 ...
   * latitude           (latitude) float64 -90, -80, -70, ...
Dimensions without coordinates: measurement_number
Data variables:
    temperature        (measurement_number, altitude, longitude, latitude) float32 ...

I tried to get to here by using ds.set_coords(['longitude','latitude']), and lots of different functions, but I cannot make the temperature depending on longitude and latitude. Can you give me a tip how to approach this problem?

Upvotes: 3

Views: 5147

Answers (1)

lasnesan
lasnesan

Reputation: 174

Have you seen the Multi-index feature in xarray? It may not be exactly what you are looking for and there are some limitations (e.g. serialisation to netCDF is not yet supported as far as i know), but maybe that is okay for you. The idea is to turn measurement_number into a pandas multiindex with latitude and longitude as virtual coordinates. You can then use .sel on multiindex coordinates aswell -> Multi-level indexing

Upvotes: 3

Related Questions