Change dimension and values of netcdf file in Python

Viewed 205

I'm trying to change the dimension of values in netcdf file.

First I read a netcdf file and interpolated the data.

import numpy as np
import netCDF4
from scipy.interpolate import interp1d

def interpolation(a,b,c):
    f = interp1d(a,b,kind='linear')
    return f(c)

file = 'directory/test.nc'
data = netcdf4.Dataset(file)

lon = data.variables['lon']  # size = 10
lat = data.variables['lat']  # size = 10
lev = data.variables['lev']  # size = 100
values = data.variables['values'] # size = (100,10,10)

new_lev = np.linspace(0,1,200) # new vertical grid size = 200

new_values = np.full(len(new_lev), len(lat), len(lon)) # size = (200,10,10)

### interpolation ###
for loop_lat in range(len(lat)):
    for loop_lon in range(len(lon)):
        new_values[:, loop_lat, loop_lon] = interpolation(lev, values[:,loop_lat,loop_lon], new_lev)


## how can I save these new_lev and new_values in the netcdf file ?

Using the interpolation, I converted the values of dimension A to dimension B.

Let say the original dimension A is 100 and interpolated dimension B is 200.

After the changing dimension, how can I save this values and dimension into netcdf file?

Could you please give me some advise?

1 Answers
Related