0

I have a NetCDF that has multiple pieces pollution data across U.S. in a daily value format. I am hoping to subtract a background variable ('nosmoke background PM25') from another ('PM25') then average this result to create an annual value. From what I understand, by creating an annual value I change my array from three dimensions (time, lat, long) to two (lat, long) since there is now no daily values. I am then hoping to subset this variable to only include a region of interest. Below is my code. Any help is much appreciated.

import netCDF4 as nc
import numpy as np
 
fn = '24hr_SmokePM25_2018.nc'
ds = nc.Dataset(fn)

#All data defining total PM25
TOT_PM25 = ds.variables['PM25']
NS_BKGD_PM25 = ds.variables['nosmoke background PM25']

#create empty array that is same size as TOT_PM25 variable to fill
Smoke_PM25 = np.full_like(TOT_PM25,0)

#For loop in subtracting total PM25 from no smoke PM25
for i in range (1,365):
    Smoke2_PM25[i,:,:]=TOT_PM25[i,:,:]-NS_BKGD_PM25[i,:,:]

#Averaging and squeezing daily value
np.mean(Smoke2_PM25[i,:,:])
np.squeeze(Smoke2_PM25, axis=0)

#boundary input for desired region to pull
latbounds = [ 24 , 39 ]
lonbounds = [ -96 , -77 ]
lons = ds.variables['lon'][:]
lats = ds.variables['lat'][:]

# latitude lower and upper index
latli = np.argmin( np.abs( lats - latbounds[0] ) )
latui = np.argmin( np.abs( lats - latbounds[1] ) ) 

# longitude lower and upper index
lonli = np.argmin( np.abs( lons - lonbounds[0] ) )
lonui = np.argmin( np.abs( lons - lonbounds[1] ) )  

# Value subsets (SmokeP25, latitude, longitude) 
Smoke_Region_PM25 = ds.variables['PM25'][ : , latli:latui , lonli:lonui ] 

#Close the NetCDF
ds.close()

1 Answer 1

1

You can do this easily with v0.3.0 of my nctoolkit package (https://pypi.org/project/nctoolkit/).

First read the data in:

import nctoolkit as nc
fn = '24hr_SmokePM25_2018.nc'
data = nc.open_data(fn)

Then subtract one variable from the other to create your new variable:

data.assign(new = lambda x: x.PM25 - x.nosmoke_background_PM25)

Once that is done you can calculate an annual mean:

data.tmean("year")

Then visualize the results:

data.plot("new")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.