-1

I am trying to create a nc file from excel file containing values in three column (lat, long and Precipitation). The data is gridded value of 0.05 degree resolution. The total number of grids is 1694. The data extent is 57 columns and 52 rows. I am not getting how to load the precipitation variable?.

I tried like this.

from netCDF4 import *
from numpy import *
from openpyxl import *
import time

#Load the data sheet
wb = load_workbook('D:\\R_Workspace\\UB_Try.xlsx')
ws = wb['UB_details']

#To get the prec variable
ppt = []
for i in range(2,1696):
   ppt.append(ws.cell(row=i,column=3).value)
ppt_arr = asarray(ppt)

#Writing nc file
nc_file = Dataset('D:\\R_Workspace\\Test.nc','w',format='NETCDF4_CLASSIC')
nc_file.description = 'Example dataset'
nc_file.history = 'Created on ' +time.ctime(time.time())

#Defining dimensions
lon = nc_file.createDimension('lon',57)
lat = nc_file.createDimension('lat',52)

#Creating variables
latitude = nc_file.createVariable('Latitude',float32,('lat',))
latitude.units = 'Degree_North'
longitude = nc_file.createVariable('Longitude',float32,('lon',))
longitude.units = 'degree_East'
prec = nc_file.createVariable('prec',float32,('lon','lat'),fill_value = -9999.0)
prec.units = 'mm'

#Writing data to variables
lats = arange(16.875,19.425,0.05)
lat_reverse = lats[::-1]
lons = arange(73.325,76.175,0.05)
latitude[:] = lat_reverse
longitude[:] = lons
prec[:] = ppt_arr
nc_file.close()

I got the error

Traceback (most recent call last):
  File "D:\R_Workspace\Try.py", line 45, in <module>
    prec[:] = ppt_arr
  File "netCDF4\_netCDF4.pyx", line 4358, in netCDF4._netCDF4.Variable.__setitem__
ValueError: cannot reshape array of size 1694 into shape (57,52)
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
Diwan
  • 1
  • 3
  • Please specify *It is not working*. Show the traceback, if any, or the wrong output etc., i.e. provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – Mike Müller Feb 07 '18 at 16:40
  • Thank you @MikeMüller I have mentioned the trackback in my query. actually my excel sheet has three column and 1964 rows excluding header. – Diwan Feb 07 '18 at 16:47
  • *The total number of grids is 1694. The data extent is 57 columns and 52 rows.* But: `57 * 52 = 2964` – Mike Müller Feb 07 '18 at 16:47
  • Yes @MikeMüller. actually it is a spatial dataand only 1694 grids has a value. remaining no data – Diwan Feb 07 '18 at 16:51
  • @MikeMüller I just replace with your line but sir that is writing all zero value – Diwan Feb 07 '18 at 17:09

1 Answers1

0

Replace this line:

prec[:] = ppt_arr

with:

temp = np.zeros(52 * 57, dtype=np.float32)
temp[:ppt_arr.size] = ppt_arr
prec[:] = temp

This creates a temporary array of zeros and fills the number of valid element with your values for pt_arr before assigning to the netCDF array.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161