我正在尝试从包含三列(lat,long和Precipitation)值的excel文件创建一个nc文件。数据是0.05度分辨率的网格值。网格总数为1694.数据范围为57列和52行。我没有得到如何加载降水变量?
我试过这样的。
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()
我收到了错误
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)
答案 0 :(得分:0)
替换此行:
prec[:] = ppt_arr
使用:
temp = np.zeros(52 * 57, dtype=np.float32)
temp[:ppt_arr.size] = ppt_arr
prec[:] = temp
这将创建一个临时的零数组,并在分配给netCDF数组之前用pt_arr
的值填充有效元素的数量。