Reputation: 13
I'm getting an error when trying to write the output from a metpy calculation to a netcdf file using xarray:
TypeError: Argument 'data' has incorrect type (expected numpy.ndarray, got Quantity)
This seems like its a result of metpy including unit information, and turning the data of the variable into a Pint.Quantity, rather than a np.ndarray, but I can't figure out a way to convert between the two while keeping it in xarray (which I want to do to maintain the coordinate data).
Here's example code (using NCEP air temperature reanlysis):
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')
This gives the error:
TypeError: Argument 'data' has incorrect type (expected numpy.ndarray, got Quantity)
after doing the theta calculation, data looks like:
<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 reanalysis\n(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....
Is it possible to get the output from the metpy calculation to write to netCDF?
Upvotes: 1
Views: 740
Reputation: 5863
I've been completely unable to reproduce the error you are encountering, though I know this was certainly a problem at some point, so you might want to consider updating your versions of metpy, xarray, numpy, and pint to the latest available versions.
Without that, though, as noted in MetPy's Xarray tutorial, you should be able to do:
data.metpy.dequantify()
to turn all DataArray
s that are holding Quantity
instances back into their base (numpy-array-backed) versions).
Upvotes: 1