Search code examples
netcatunits-of-measurementmasked-arraymetpy

How to keep the same units from my precipitation data when using masked_array?


I am attempting to create a precipitation map with one nc file, similar to a NWS example that I found here.

In my case, though, my precipitation data is already in mm. How do I keep the same units? I did read the following,

Create a numpy.ma.MaskedArray with units attached. This is a thin wrapper around numpy.ma.masked_array() that ensures that units are properly attached to the result (otherwise units are silently lost). Units are taken from the data_units argument, or if this is None, the units on data are used.

I followed the parameters given (masked_array(data, data_units=None, **kwargs)) for my file, but

  1. kwargs is not defined, and
  2. when I don't include kwargs, I get

"AttributeError: 'MaskedArray' object has no attribute 'units'".

I am a beginner, so please be gentle. Thank you for your guidance! Here is my code...

from netCDF4 import Dataset as NetCDFFile
import matplotlib.pyplot as plt
import numpy as np
import cartopy
import cartopy.crs as ccrs
import cartopy.feature as cf
import matplotlib.colors as mcolors
from metpy.units import masked_array, units

nc_data = NetCDFFile(r'C:\Users\Jocelyn\Desktop\TRMM_daily_prcp_data\3B42_Daily.19980601.7.nc4', 'r')

print (nc_data)
print(nc_data.variables.keys()) 

prcp = nc_data.variables['precipitation']
data = masked_array(prcp[:], prcp_units=None, **kwargs)
lat = nc_data.variables['lat']
lon = nc_data.variables['lon']

Solution

  • If you're not trying to use MetPy calculations with your precipitation data and you don't need to do any unit conversion, then you should be able to eliminate the use of masked_array altogether. So try this:

    prcp = nc_data.variables['precipitation']
    data = prcp[:]
    lat = nc_data.variables['lat']
    lon = nc_data.variables['lon']