【问题标题】:How can I extract a 1d array of all combinations of Xarray coordinates?如何提取 Xarray 坐标的所有组合的一维数组?
【发布时间】:2020-03-11 01:47:54
【问题描述】:

我正在尝试从 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() 时变得更强大,然后上述函数将仅返回数据集不是 NaN 的一维数组或坐标列表给定的查询。

xarray 中是否存在类似的东西,还是我需要自己实现解决方案?

【问题讨论】:

    标签: python indexing coordinates tensor python-xarray


    【解决方案1】:
    #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 可以是 where 已经支持的任何查询。同样,在.stack() 调用中,如果您有更多维度,您可以指定更多维度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 2019-07-07
      • 2017-09-25
      • 2017-10-10
      • 1970-01-01
      • 2020-06-08
      • 2018-01-11
      相关资源
      最近更新 更多