0

I have a dataset that is dimensioned by time and id but it also has lat and lon coordinates.

The data variable is dimensioned by time and id and what I want to do is dimension it by time, lat, and lon. For example:

import numpy
import xarray

ds = xarray.Dataset()
ds['data'] = (('time', 'id'), numpy.arange(0, 50).reshape((5, 10)))

ds.coords['time'] = (('time',), numpy.arange(0, 5))
ds.coords['id'] = (('id',), numpy.arange(0, 10))

ds.coords['lat'] = (('lat',), numpy.arange(10, 20))
ds.coords['lon'] = (('lon',), numpy.arange(20, 30))

print ds

Result:

<xarray.Dataset>
Dimensions:  (id: 10, lat: 10, lon: 10, time: 5)
Coordinates:
  * time     (time) int64 0 1 2 3 4
  * id       (id) int64 0 1 2 3 4 5 6 7 8 9
  * lat      (lat) int64 10 11 12 13 14 15 16 17 18 19
  * lon      (lon) int64 20 21 22 23 24 25 26 27 28 29
Data variables:
    data     (time, id) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ...

The only way I can figure out how to accomplish this is to iterate over the indexes building out a new data array with the correct shape and dimensions:

reshaped_array = numpy.ma.masked_all((5, 10, 10))
for t_idx in range(0, 5):
    for r_idx in range(0, 10):
        reshaped_array[t_idx, r_idx, r_idx] = ds['data'][t_idx, r_idx]

ds['data2'] = (('time', 'lat', 'lon'), reshaped_array)

print ds

Result:

<xarray.Dataset>
Dimensions:  (id: 10, lat: 10, lon: 10, time: 5)
Coordinates:
  * time     (time) int64 0 1 2 3 4
  * id       (id) int64 0 1 2 3 4 5 6 7 8 9
  * lat      (lat) int64 10 11 12 13 14 15 16 17 18 19
  * lon      (lon) int64 20 21 22 23 24 25 26 27 28 29
Data variables:
    data     (time, id) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ...
    data2    (time, lat, lon) float64 0.0 nan nan nan nan nan nan nan nan ...

But this is very expensive, is there a better way? Basically at each 'time' slice I want a diagonal array that is filled with the values from the original data. It seems like I should be able to construct a view into the original data somehow to accomplish this but I'm at a loss as to how to do it.

4

1 回答 1

1

你不需要for循环:

res = np.full((5, 10, 10), np.nan)
idx = np.arange(10)
res[:, idx, idx] = ds['data']
ds['data2'] = (('time', 'lat', 'lon'), res)
于 2018-03-02T01:45:23.373 回答