获取xarray数据集的非nan值的坐标

时间:2016-11-14 15:45:53

标签: numpy python-xarray

我有这个样本数据集包含全球气温,更重要的是,掩护land,标记陆地/非水域。

<xarray.Dataset>
Dimensions:  (lat: 55, lon: 143, time: 5)
Coordinates:
  * time     (time) datetime64[ns] 2016-01-01 2016-01-02 2016-01-03 ...
  * lat      (lat) float64 -52.5 -50.0 -47.5 -45.0 -42.5 -40.0 -37.5 -35.0 ...
  * lon      (lon) float64 -177.5 -175.0 -172.5 -170.0 -167.5 -165.0 -162.5 ...
    land     (lat, lon) bool False False False False False False False False ...
Data variables:
    airt     (time, lat, lon) float64 7.952 7.61 7.389 7.267 7.124 6.989 ...

我现在可以掩盖海洋并绘制它

dry_areas = ds.where(ds.land)
dry_areas.airt.plot()

Plot land areas only dry_areas看起来像这样

<xarray.Dataset>
Dimensions:  (lat: 55, lon: 143)
Coordinates:
  * lat      (lat) float64 -52.5 -50.0 -47.5 -45.0 -42.5 -40.0 -37.5 -35.0 ...
  * lon      (lon) float64 -177.5 -175.0 -172.5 -170.0 -167.5 -165.0 -162.5 ...
    land     (lat, lon) bool False False False False False False False False ...
Data variables:
    airt     (lat, lon) float64 nan nan nan nan nan nan nan nan nan nan nan ...

我现在如何获取所有非纳米值的坐标?

dry_areas.coords给了我一个边界框,我无法将纬度和lon变成(55, 143)形状,因此我可以应用蒙版。

我能找到的唯一可行的解​​决方法是 dry_areas.to_dataframe().dropna().reset_index()[['lat', 'lon']].values,感觉不那么瘦和干净。

我觉得这很简单,但我显然不是一个numpy /矩阵忍者。

目前为止的最佳解决方案

这是我到目前为止最短的时间:

lon, lat = np.meshgrid(ds.coords['lon'], ds.coords['lat'])
lat_masked  = ma.array(lat, mask=dry_areas.airt.fillna(False))
lon_masked  = ma.array(lon, mask=dry_areas.airt.fillna(False))
land_coordinates = zip(lat_masked[lat_masked.mask].data,     lon_masked[lon_masked.mask].data)

1 个答案:

答案 0 :(得分:2)

您可以使用.stack获取非空值的coord对数组:

In [31]: da=xr.DataArray(np.arange(20).reshape(5,4))
In [33]: da_nans = da.where(da % 2 == 1)
In [34]: da_nans
Out[34]:
<xarray.DataArray (dim_0: 5, dim_1: 4)>
array([[ nan,   1.,  nan,   3.],
       [ nan,   5.,  nan,   7.],
       [ nan,   9.,  nan,  11.],
       [ nan,  13.,  nan,  15.],
       [ nan,  17.,  nan,  19.]])
Coordinates:
  * dim_0    (dim_0) int64 0 1 2 3 4
  * dim_1    (dim_1) int64 0 1 2 3

In [35]: da_stacked = da_nans.stack(x=['dim_0','dim_1'])

In [36]: da_stacked
Out[36]:
<xarray.DataArray (x: 20)>
array([ nan,   1.,  nan,   3.,  nan,   5.,  nan,   7.,  nan,   9.,  nan,
        11.,  nan,  13.,  nan,  15.,  nan,  17.,  nan,  19.])
Coordinates:
  * x        (x) object (0, 0) (0, 1) (0, 2) (0, 3) (1, 0) (1, 1) (1, 2) ...


In [37]: da_stacked[da_stacked.notnull()]
Out[37]:
<xarray.DataArray (x: 10)>
array([  1.,   3.,   5.,   7.,   9.,  11.,  13.,  15.,  17.,  19.])
Coordinates:
  * x        (x) object (0, 1) (0, 3) (1, 1) (1, 3) (2, 1) (2, 3) (3, 1) ...