hlee
hlee

Reputation: 343

Expanding coordinates of a variable using other two variables of xarray in Python

Let's say I have data of 16 grid cells (4 * 4) which has a corresponding index (0~15) as dimension & coordinates and variables (a, longitude and latitude) for each cell. Here is the code to create this data.

import xarray as xr
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(16,3), \
                  columns=['a','longitude', 'latitude'], \
                  index=range(16))
ds = df.to_xarray()
ds

What I want to do is:

Expand the coordination of data a from (index) to (longitude, latitude) using longitude and latitude variables of each cell.
So, the resulting DataSet will include longitude and latitude as its dimension and coordinates as well as variable a of (longitude, latitude)
How can I do this within xarray functionality?
Thanks!

Upvotes: 0

Views: 204

Answers (1)

hlee
hlee

Reputation: 343

Here is a way to solve that:

# convert the index as a MultiIndex containing longitude and latitude
dat_2d = ds.set_index({'index': ['longitude', 'latitude']})

# unstack the MultiIndex
unstacked = dat_2d.unstack('index')

# plot
unstacked['a'].plot()

Upvotes: 0

Related Questions