簡體   English   中英

使用 xarray 獲取 netcdf 文件的平均值

[英]get mean of netcdf file using xarray

我使用 xarray 在 python 中打開了一個 netcdf 文件,數據集摘要如下所示。

Dimensions:    (latitude: 721, longitude: 1440, time: 41)
Coordinates:
  * longitude  (longitude) float32 0.0 0.25 0.5 0.75 ... 359.25 359.5 359.75
  * latitude   (latitude) float32 90.0 89.75 89.5 89.25 ... -89.5 -89.75 -90.0
    expver     int32 1
  * time       (time) datetime64[ns] 1979-01-01 1980-01-01 ... 2019-01-01
Data variables:
    z          (time, latitude, longitude) float32 50517.914 ... 49769.473
Attributes:
    Conventions:  CF-1.6
    history:      2020-03-02 12:47:40 GMT by grib_to_netcdf-2.16.0: /opt/ecmw...

我想得到沿緯度和經度維度的 z 值的平均值。

我嘗試使用此代碼:

df.mean(axis = 0)

但它正在刪除時間坐標,並返回給我這樣的東西。

Dimensions:  (latitude: 721, longitude: 1440)
Coordinates:
    expver   int32 1
Dimensions without coordinates: latitude, longitude
Data variables:
    z        (latitude, longitude) float32 49742.03 49742.03 ... 50306.242

我在這里做錯了什么。 請幫我解決一下這個。

警告!!! 如果您沿緯度應用它,接受的答案將給您錯誤的結果(您需要這樣做才能完全回答問題),因為您需要對每個單元格進行加權,它們的大小不同,並且隨着您移向規則緯度網格中的極點。

Xarray 解決方案:

因此,要進行加權平均,您需要按照以下代碼構建權重:

import numpy as np
weights = np.cos(np.deg2rad(df.z))
weights.name = "weights"
z_weighted = df.z.weighted(weights)
weighted_mean = z_weighted.mean(("longitude", "latitude"))

有關更多詳細信息和示例比較,請參閱 xarray 文檔中的此討論。

誤差的大小取決於您正在平均的區域,以及變量在緯度方向上的梯度有多強 - 緯度范圍和變量梯度中的區域越大,情況越糟......對於一個全局溫度場 這是 xarray 文檔中的示例錯誤,遠遠超過 5degC! 未加權的答案更冷,因為即使那里的網格單元小得多,極點的計數也是相等的。

在此處輸入圖片說明

替代 CDO 解決方案

順便說一句,順便說一句,您也可以像這樣從命令行使用 cdo 執行此操作

cdo fldmean in.nc out.nc 

cdo 考慮了網格,因此您無需擔心權重問題。

您需要按維度 ( dim ) 而不是axis

使用df.mean(dim='longitude')

暫無
暫無

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

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