簡體   English   中英

如何將自定義 function 應用於 xarray.DataArray.coarsen.reduce()?

[英]How to apply a custom function to xarray.DataArray.coarsen.reduce()?

我有一個 (2x2) NumPy 數組:

ar = np.array([[2, 0],[3, 0]])

和 xarray.DataArray 形式的相同:

da = xr.DataArray(ar, dims=['x', 'y'], coords=[[0, 1], [0, 1]])

我正在嘗試使用自定義 function 在空間上對二維數組進行下采樣以查找模式(即最常出現的值):

def find_mode(window):
    # find the mode over all axes 
    uniq = np.unique(window, return_counts=True)
    return uniq[0][np.argmax(uniq[1])]

find_mode()適用於ar ,因為find_mode(ar)給出0

但是,它不適用於da (即da.coarsen(x=2, y=2).reduce(find_mode) ),並出現錯誤:

TypeError: find_mode() got an unexpected keyword argument 'axis'

非常感謝您的關注和參與。

傳遞給DatasetCoarsen.reduce的函數的簽名必須包括axiskwargs 一個很好的例子是np.sum 所以你的 function 需要看起來像:

def find_mode(window, axis=None, **kwargs):
    # find the mode over all axes 
    uniq = np.unique(window, return_counts=True)
    
    ret = uniq[0][np.argmax(uniq[1])]
    ret = np.atleast_2d(ret)

    return ret

根據您的應用程序,您可能希望使用axis參數(整數元組)代替[0][1]索引步驟。

注意:我在這里添加了np.atleast_2d以確保返回數組是二維的。 這有點難看,所以我建議在您的應用程序中多考慮一下這部分。 要理解的關鍵是返回數組需要與輸入數組具有相同的維數。

暫無
暫無

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

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