簡體   English   中英

按 3D xarray 中的月份編號訪問數據

[英]Access data by month number in 3D xarray

我有給定年份的 1 月、2 月、3 月、4 月、10 月、11 月和 12 月的數據數組 (361x361)。

到目前為止,我一直將它們存儲在一年中每個月的單獨 netcdf 中(例如 03.nc、10.nc)

我想將所有月份合並為一個 netcdf,以便我可以執行以下操作:

march_data = data.sel(month='03') 

或者data.sel(month=3))

到目前為止,我只能將每月數據堆疊在一個 361x361x7 的數組中,並且它的索引無濟於事,因此要獲得 3 月的數據,您需要執行 data[:,:,2] 並獲得 10 月的數據 [:,:, 4]。 顯然,2 和 4 並不直觀地對應於三月和十月。 這部分是因為 python 從零開始索引,部分是因為我錯過了夏季月份。 我可以將 nan 字段放入缺失的月份,但這並不能解決 index-0 問題。

到目前為止我的嘗試:

 data = xarray.Dataset( data_vars={'ice_type':(['x','y','time'],year_array),},
                      coords={'lon':(['x','y'],lon_target),
                              'lat':(['x','y'],lat_target),
                              'month_number':(['time'],month_int)})

這里year_array是一個 361x361x7 numpy 數組,而month_int是一個列表,它將year_array的第三個索引year_array到月份編號: [1,2,3,4,10,11,12]

當我嘗試使用oct = data.sel(month_number=10)獲取 Oct 數據時,它會引發錯誤。

在一個側面說明,我知道,有可能被發現的解決方案在這里,但說實話,我不明白它是如何工作的。 我的困惑主要是基於他們如何同時使用“時間”作為字典鍵和時間列表。

我想我已經寫了一個輔助函數來做這樣的事情:

def combine_new_ds_dim(ds_dict, new_dim_name):
    """
    Combines a dictionary of datasets along a new dimension using dictionary keys
    as the new coordinates.

    Parameters
    ----------
    ds_dict : dict
        Dictionary of xarray Datasets or dataArrays
    new_dim_name : str
        The name of the newly created dimension

    Returns
    -------
    xarray.Dataset
        Merged Dataset or DataArray

    Raises
    ------
    ValueError
        If the values of the input dictionary were of an unrecognized type
    """

    expanded_dss = []

    for k, v in ds_dict.items():
        expanded_dss.append(v.expand_dims(new_dim_name))
        expanded_dss[-1][new_dim_name] = [k]
    new_ds = xr.concat(expanded_dss, new_dim_name)

    return new_ds

如果您在單獨的 netcdfs 中擁有所有數據,那么您應該能夠將它們導入到單獨的dataArray 假設你已經這樣做了,那么你可以做

month_das = {
    1: january_da,
    2: february_da,
    ...
    12: december_da
}

year_data = combine_new_ds_dim(month_das, 'month')

這將是沿新維度month的所有數據與所需坐標的串聯。 如果你想單獨使用它,我認為函數的主循環很容易分開。

編輯:

對於將來看到這個的任何人來說,使用內置的 xarray 函數有一種更簡單的方法來做到這一點。 您可以沿着新維度串聯

year_data = xr.concat([january_da, february_da, ..., december_da], dim="month")

這將創建一個新的dataArray其中包含沿新維度連接的組成數組,但在該維度上沒有坐標。 要添加坐標,

year_data["month"] = [1, 2, ..., 12]

此時year_data將沿新維度“月”連接,並沿該維度具有所需的坐標。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM