Expand dimensions xarray

↘锁芯ラ 提交于 2019-12-10 19:17:59

问题


Is there an existing method or approach to expand the dimensions (and coordinates) of an xarray.DataArray object?

I would like to obtain something similar to np.expand_dims while at the same time defining a new dimension and coordinate variable for the new expanded DataArray.

Using DataArray.assign_coords() I can create a new coordinate variable but the array itself is not expanded with a new axis.


回答1:


In xarray v0.10.0, I use a combination of assign_coords() and expand_dims() to add a new dimension and coordinate variable.

For example:

import xarray as xr
import numpy as np
data = xr.DataArray([1, 2, 3], dims='x', coords={'x': [10, 20, 30]})
data_newcoord = data.assign_coords(y='coord_value')
data_expanded = data_newcoord.expand_dims('y')
print(data_expanded)
# <xarray.DataArray (y: 1, x: 3)>
# array([[1, 2, 3]])
# Coordinates:
#   * x        (x) int64 10 20 30
#   * y        (y) <U11 'coord_value'



回答2:


I agree that some sort of method for doing this would be useful. It does not currently exist directly in xarray, but I would encourage you to file an issue on GitHub to discuss API for a new feature and/or make a pull request implementing it.

The new xarray.broadcast function contains some related functionality that may suffice for this purposes:

import xarray as xr
import numpy as np
data = xr.DataArray([1, 2, 3], dims='x')
other = xr.DataArray(np.zeros(4), coords=[('y', list('abcd'))])
data2, other2 = xr.broadcast(data, other)
print(data2)
# <xarray.DataArray (x: 3, y: 4)>
# array([[1, 1, 1, 1],
#       [2, 2, 2, 2],
#       [3, 3, 3, 3]])
# Coordinates:
#   * x        (x) int64 0 1 2
#   * y        (y) |S1 'a' 'b' 'c' 'd'


来源:https://stackoverflow.com/questions/34987972/expand-dimensions-xarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!