0
votes

I want to convert a NetCDF file to CSV format. I have tried the forum for some help, but could not get what I want. I have three variables, a 1D latitude array, 1D longitude array and a 2D variable array. Is it possible to get a CSV format file with columns like LAT, LON, VAR?

I have tried using pandas Dataframe.

    from netCDF import Dataset
    data = Dataset('popd.nc')

    latd=data.variables['latitude']
    longd=data.variables['longitude']
    popd = data.variables['PopD'][3] # 2D array

    popd2015 = pd.DataFrame(popd,index=latd,columns=longd)
    popd2015.to_csv('popd2015.csv',index=True,header=True)

The result is a 2d array of my variable with columns at latitude and rows as longitude. But I expect something like three columns with LAT, LON, VAR.

1

1 Answers

1
votes

You could find one solution from:

How to match netCDF variables' values in an array in MATLAB

but here is the short part:

# =============================================
def ncread(filename,varname):
    ncin=Dataset(filename);
    vardata = ncin.variables[varname][:];
    ncin.close()
    return vardata
# ---------------------------------------------
# Convert to text:
filein = 'popd.nc'
lonin=ncread(filein,'longitude'); # read longitude
latin=ncread(filein,'latitude'); # read latitude
popin=ncread(filein,'PoPD'); # read data
# ---------------------------------------------
latm,lonm = np.meshgrid(latin,lonin); 
# ---------------------------------------------
dataout=np.concatenate((lonm.flatten()[:,np.newaxis],latm.flatten()[:,np.newaxis],popin.flatten()[:,np.newaxis]),axis=1) # make one matrice from all the data
np.savetxt('test.txt',dataout); # save data
# ==============================================

Without data I cannot guarantee that it works, but in case you should get the idea how to do that.