新数组的总大小必须不变(netCDF)

时间:2016-02-26 14:17:07

标签: python csv numpy netcdf

我无法将CSV文件转换为NetCDF。我在Python中使用numpy和netCDF4来尝试实现这一点。

错误:

Traceback (most recent call last):
File "csv2nc.py", line 47, in <module>
tmaxsfc[:] = temps
File "netCDF4.pyx", line 3167, in netCDF4.Variable.__setitem__ (netCDF4.c:39349)
ValueError: total size of new array must be unchanged

脚本:

import numpy as np
import netCDF4

data = np.loadtxt('/home/weather/Dropbox/d0_tmaxs', delimiter=',', skiprows=0)

temp = data[:,1]
lat = data[:,2]
lon = data[:,3]

with netCDF4.Dataset('tmaxsfc.nc', mode="w", format='NETCDF4') as ds:
# some file-level meta-data attributes:
ds.Conventions = "CF-1.6"
ds.title = 'Maximum Temperature values for Day 0'
ds.institution = 'weather'
ds.source = ''

#print(lon.shape)

lats = np.array(lat,np.float32).reshape(255)
lons = np.array(lon,np.float32).reshape(255)
temps = np.array(temp,np.float32).reshape(255)

ds.createDimension('latitude', 255)
ds.createDimension('longitude', 255)

tmaxsfc = ds.createVariable('tmaxsfc', 'f4', ('latitude', 'longitude',))
tmaxsfc[:] = temps
tmaxsfc.units = 'F'
tmaxsfc.long_name = 'Temperature'

d0_tmaxs文本文件示例:

20160226,40,36.65408,-83.21783
20160226,35.1508,41.00928,-74.73628
20160226,31,43.77714,-71.75598
20160226,23.8302,44.41944,-72.01944
20160226,22,39.5803,-79.3394

对于它的价值,文本文件有255行。我做错了什么?

2 个答案:

答案 0 :(得分:0)

我在netcdf上有点生疏,但没有

tmaxsfc = ds.createVariable('tmaxsfc', 'f4', ('latitude', 'longitude',))

表示tmaxsfc是2维数组,255乘255?您是在经纬度的纬度网格上定义它。

但看起来您的输入会显示在散点图上,255个点,每个点由纬度,经度和温度定义。

答案 1 :(得分:0)

因此错误来自temp是具有255个元素的一维数组,但tmaxsfc变量被定义为2D变量。你想要做的是创建一个维度,比如说station,所有3个1D变量都可以是:

import numpy as np
import netCDF4

data = np.loadtxt('/home/weather/Dropbox/d0_tmaxs', delimiter=',', skiprows=0)

temp = np.array(data[:,1], dtype=np.float32).reshape(255)
lat = np.array(data[:,2], dtype=np.float32).reshape(255)
lon = np.array(data[:,3], dtype=np.float32).reshape(255)

with netCDF4.Dataset('tmaxsfc.nc', mode="w", format='NETCDF4') as ds:
    # some file-level meta-data attributes:
    ds.Conventions = "CF-1.6"
    ds.title = 'Maximum Temperature values for Day 0'
    ds.institution = 'weather'
    ds.source = ''

    ds.createDimension('station', 255)
    dims = ('station',)

    tmaxsfc = ds.createVariable('tmaxsfc', np.float32, dims) 
    tmaxsfc[:] = temps
    tmaxsfc.units = 'F'
    tmaxsfc.long_name = 'Temperature'

    lon_var = ds.createVariable('longitude', np.float32, dims)
    lon_var[:] = lon
    lon.units = 'degrees_east'

    lat_var = ds.createVariable('latitude', np.float32, dims)
    lat_var[:] = lat
    lat.units = 'degress_north'