尝试使用xarray将metpy计算的输出写入netcdf文件时出错:TypeError: Argument 'data' has incorrect type (expected numpy.ndarray, got Quantity)
这似乎是由于metpy包含了单位信息,并将变量的数据转换为Pint.Quantity,而不是np.ndarray,但我无法找到在将其保留在xarray中的同时在两者之间进行转换的方法(我想这样做以维护坐标数据(。
以下是示例代码(使用NCEP空气温度再分析(:
import xarray as xr
import metpy.calc as mpcalc
data = xr.open_dataset('air.2005.nc')
data['theta'] = mpcalc.potential_temperature(data['level'], data['air'])
data.to_netcdf('theta.2005.nc')
这会产生错误:TypeError: Argument 'data' has incorrect type (expected numpy.ndarray, got Quantity)
在进行θ计算后,数据看起来像:
<xarray.Dataset>
Dimensions: (lat: 91, level: 17, lon: 180, time: 365)
Coordinates:
* time (time) datetime64[ns] 2005-01-01 2005-01-02 ... 2005-12-31
* lon (lon) float64 -180.0 -178.0 -176.0 -174.0 ... 174.0 176.0 178.0
* lat (lat) float64 -90.0 -88.0 -86.0 -84.0 -82.0 ... 84.0 86.0 88.0 90.0
* level (level) float32 1e+03 925.0 850.0 700.0 ... 50.0 30.0 20.0 10.0
Data variables:
air (time, level, lat, lon) float32 ...
theta (level, time, lat, lon) float32 <Quantity([[[[272.32 272.32 ...
Attributes:
CDI: Climate Data Interface version 1.9.8 (https://mpimet.mpg....
Conventions: COARDS
history: Wed Nov 25 14:51:47 2020: cdo remap,twoDegreeGrid,remapwe...
title: 4x daily NMC reanalysis (2005)
description: Data is from NMC initialized reanalysisn(4x/day). It co...
platform: Model
References: http://www.esrl.noaa.gov/psd/data/gridded/data.ncep.reana...
dataset_title: NCEP-NCAR Reanalysis 1
CDO: Climate Data Operators version 1.9.8 (https://mpimet.mpg....
是否可以从metpy计算中获得输出以写入netCDF?
我完全无法重现您遇到的错误,尽管我知道这在某个时候肯定是个问题,所以您可能需要考虑将metpy、xarray、numpy和pint的版本更新到最新的可用版本。
不过,如果没有这一点,正如MetPy的Xarray教程中所指出的,您应该能够做到:
data.metpy.dequantify()
以将持有Quantity
实例的所有DataArray
转回到它们的基本(numpy阵列支持的(版本(。