Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Xarray, sort by index or dimension?

Tags:

Is there a sort_index or sort_by_dimension method of some kind in xarray, much like pandas.DataFrame.sort_index(), where I can sort a xarray.DataArray object by one of its dimensions? In terms of usage, I'm thinking of something like data_array.sort(dim="dimension_name").

like image 953
Ray Avatar asked Nov 16 '16 15:11

Ray


1 Answers

I couldn't find a good method to do this built into xarray, so I made a new array by taking a slice with the sorted values from the coordinate I wanted to sort: da_sorted=da.loc[{'lon':sorted(da.coords['lon'].values)}]

Here's a larger example with test data showing what it looks like in practice:

import numpy as np
import xarray as xr

data = np.random.rand(2, 3)

lat = [47, 45]

lon = [-118, -122, -120]
da = xr.DataArray(data, coords=[lat, lon], dims=['lat', 'lon'])


>>>> da
<xarray.DataArray (lat: 2, lon: 3)>
array([[ 0.16118 ,  0.215621,  0.599749],
       [ 0.144778,  0.984167,  0.416469]])
Coordinates:
  * lat      (lat) int64 47 45
  * lon      (lon) int64 -118 -122 -120,


da_sorted = da.loc[{'lon':sorted(da.coords['lon'].values)}]
>>>> da_sorted
<xarray.DataArray (lat: 2, lon: 3)>
array([[ 0.215621,  0.599749,  0.16118 ],
       [ 0.984167,  0.416469,  0.144778]])
Coordinates:
  * lat      (lat) int64 47 45
  * lon      (lon) int64 -122 -120 -118
like image 71
Kyle Heuton Avatar answered Sep 24 '22 16:09

Kyle Heuton