首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >尝试创建.nc文件时在netCDF Python中获取ValueError

尝试创建.nc文件时在netCDF Python中获取ValueError
EN

Stack Overflow用户
提问于 2020-07-14 17:20:16
回答 1查看 80关注 0票数 0

我正在尝试将数据写入netcdf文件,使用此示例代码时,我得到以下错误:

代码语言:javascript
运行
复制
Traceback (most recent call last):
  File "netCDF4\_netCDF4.pyx", line 4866, in netCDF4._netCDF4.Variable.__setitem__
ValueError: cannot reshape array of size 5 into shape (5,1,1,3)

下面是一个你可以自己尝试的示例测试代码;

代码语言:javascript
运行
复制
from netCDF4 import Dataset

latitude = [21.1877]
longitude = [-68.95998]
depth_array = [2, 3.5, 5]  # in meters
time_array = [19022040, 19022070, 19022100, 19022130, 19022160]  # Minutes since 1970-01-01 00:00:00 UTC
pressure_array = [37.57, 37.573, 37.588, 37.597, 37.613]
temperature_array = [26.19, 26.2, 26.18, 26.19, 26.17]


current_speed_array = [[0.093, 0.109, 0.076, 0.045, 0.054],  # 2M depth
                       [0.119, 0.041, 0.113, 0.12, 0.088],  # 3.5M depth
                       [0.131, 0.116, 0.184, 0.095, 0.127]]  # 5M depth

current_dir_array = [[63.98, 62.02, 335.81, 36.87, 70.56],  # 2M depth
                     [21.18, 344.25, 3.04, 352.34, 344.23],  # 3.5M depth
                     [346.28, 353.55, 8.44, 349.64, 339.71]]  # 5M depth


dataset = Dataset("Test.nc", 'w', format="NETCDF4_CLASSIC")

# Creating Dimensions
dataset.createDimension('time', None)
dataset.createDimension('lat', 1)
dataset.createDimension('lon', 1)
dataset.createDimension('depth', len(depth_array))

# Creating Variables
times = dataset.createVariable("time", "f4", ('time',))
lats = dataset.createVariable("lat", 'd', ('lat',))
lons = dataset.createVariable("lon", 'd', ('lon',))
depths = dataset.createVariable("depth", "f8", ("depth",))
pressures = dataset.createVariable("pres", "f4", ("time", "lat", "lon", "depth",))
temperatures = dataset.createVariable("temp", "f4", ("time", "lat", "lon", "depth",))
current_speeds = dataset.createVariable("speed", "f8", ("time", "lat", "lon", "depth",))
current_directions = dataset.createVariable("dir", "f8", ("time", "lat", "lon", "depth",))

# Writing Data to Variables
times[:] = time_array
lats[:] = latitude
lons[:] = longitude
depths[:] = depth_array
pressures[:] = pressure_array
current_speeds[:] = current_speed_array
current_directions[:] = current_dir_array
dataset.close()
EN

回答 1

Stack Overflow用户

发布于 2020-07-15 11:44:50

该错误来自于pressures被定义为维度为timelatlondepth的变量,因此它的形状为5x1x1x3。您正在尝试编写pressure_array,它只有5个值,所以它不匹配。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62891879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档