如何提取 Xarray 坐标的所有组合的一维数组?
How can I extract a 1d array of all combinations of Xarray coordinates?
我正在尝试从 xarray 数据集中提取坐标值作为与原始 xarray 数据集大小相同的数组,其中每个值都是一个元组。例如,如果我有一个坐标为 x=[0,1]
和 y=[2,3]
的数据集,那么我想要 np.array([(0,2), (1,2),(0,3),(1,3)])
之类的东西。这似乎没用,因为使用标准 [(a,b) for a in x for b in y]
可以实现类似的事情,但在使用 xarray 的 ds.where()
时变得更强大,然后上面的函数只会 return 一维数组或列表对于给定查询,数据集不是 NaN 的坐标。
xarray 中目前是否存在类似的东西,或者我需要自己实施解决方案吗?
#make some fake data
np.random.seed(123)
times = pd.date_range("2000-01-01", "2001-12-31", name="time")
annual_cycle = np.sin(2 * np.pi * (times.dayofyear.values / 365.25 - 0.28))
base = 10 + 15 * annual_cycle.reshape(-1, 1)
tmin_values = base + 3 * np.random.randn(annual_cycle.size, 3)
tmax_values = base + 10 + 3 * np.random.randn(annual_cycle.size, 3)
#Example dataset from xarray examples
ds = xr.Dataset(
{
"tmin": (("time", "location"), tmin_values),
"tmax": (("time", "location"), tmax_values),
},
{"time": times, "location": ["IA", "IN", "IL"]},
)
### Solution
da_nans=ds.where(ds.tmin>0)
#create coordinate database
da_stacked=da_nans.stack(dim=['time','location])
nona_coords = da_stacked[da_stacked.notnull()].dim
以上实现了预期的结果,其中 ds.where 可以是已经支持的任何查询。同样,在 .stack()
调用中,如果您有更多维度,则可以指定更多维度。
我正在尝试从 xarray 数据集中提取坐标值作为与原始 xarray 数据集大小相同的数组,其中每个值都是一个元组。例如,如果我有一个坐标为 x=[0,1]
和 y=[2,3]
的数据集,那么我想要 np.array([(0,2), (1,2),(0,3),(1,3)])
之类的东西。这似乎没用,因为使用标准 [(a,b) for a in x for b in y]
可以实现类似的事情,但在使用 xarray 的 ds.where()
时变得更强大,然后上面的函数只会 return 一维数组或列表对于给定查询,数据集不是 NaN 的坐标。
xarray 中目前是否存在类似的东西,或者我需要自己实施解决方案吗?
#make some fake data
np.random.seed(123)
times = pd.date_range("2000-01-01", "2001-12-31", name="time")
annual_cycle = np.sin(2 * np.pi * (times.dayofyear.values / 365.25 - 0.28))
base = 10 + 15 * annual_cycle.reshape(-1, 1)
tmin_values = base + 3 * np.random.randn(annual_cycle.size, 3)
tmax_values = base + 10 + 3 * np.random.randn(annual_cycle.size, 3)
#Example dataset from xarray examples
ds = xr.Dataset(
{
"tmin": (("time", "location"), tmin_values),
"tmax": (("time", "location"), tmax_values),
},
{"time": times, "location": ["IA", "IN", "IL"]},
)
### Solution
da_nans=ds.where(ds.tmin>0)
#create coordinate database
da_stacked=da_nans.stack(dim=['time','location])
nona_coords = da_stacked[da_stacked.notnull()].dim
以上实现了预期的结果,其中 ds.where 可以是已经支持的任何查询。同样,在 .stack()
调用中,如果您有更多维度,则可以指定更多维度。