简体   繁体   English

Python netCDF:从地理区域创建离散坐标变量

[英]Python netCDF: Create discrete coordinate variable from geographical region

I'm looking to create a netCDF4 file, 'area_nc', with dimensions of time and a discrete, alphanumeric area code, eg 'A0', 'A1', 'A2', 'B0' etc, that doesn't fit to a regular grid (instead of latitude/longitude). 我正在寻找一个netCDF4文件“ area_nc”,它具有时间维度和一个离散的字母数字区号,例如“ A0”,“ A1”,“ A2”,“ B0”等,不适合常规网格(而不是经度/纬度)。

The NetCDF Climate and Forecast (CF) Metadata Conventions pdf suggests that this can be done in Section 4.5, but I can't find any examples. NetCDF气候和预报(CF)元数据约定 pdf建议可以在4.5节中完成此操作,但我找不到任何示例。

Is there a way to do this? 有没有办法做到这一点?

So far I've tried: 到目前为止,我已经尝试过:

import netCDF4 as nc

area_nc = nc.Dataset('area.nc', 'w')

area_nc.createDimension('time', None)
area_nc.createDimension('nhood', 6)

time = area_nc.createVariable('time', int, ('time'))
nhood = area_nc.createVariable('nhood', str, ('nhood'))

in_temp = area_nc.createVariable('in_temp', int, ('time', 'nhood'))

nhood[:] = ['A0', 'A1', 'A2', 'B0', 'B1', 'B2']

But I get the error: 但是我得到了错误:

IndexError: data can only be assigned to VLEN variables using integer indices

Achieving this, I would then like to add data to the file using this code as a reference, instead of an integer slice, eg: 为此,我想使用此代码作为参考,而不是整数切片,将数据添加到文件中,例如:

area_nc.variables['in_temp'][0, 'A0'] = 23

Thanks! 谢谢!

The first part of your question, the error: The error indicates that python considers your dimension to be of variable length (VLEN). 问题的第一部分,错误:错误表明python认为您的尺寸为可变长度(VLEN)。 The solution lies in better defining the dimension. 解决方案在于更好地定义尺寸。 A solution is changing two of your lines: 一种解决方案是更改您的两条生产线:

nhood = area_nc.createVariable('nhood', str, ('nhood')) ->
nhood = area_nc.createVariable('nhood', '<U13', ('nhood'))

nhood[:] = ['A0', 'A1', 'A2', 'B0', 'B1', 'B2'] ->
nhood[:] = np.array(['A0', 'A1', 'A2', 'B0', 'B1', 'B2'])

Unfortunately, your last line won't work yet still. 不幸的是,您的最后一行仍然无法正常工作。 I could think of the following workaround: 我可以想到以下解决方法:

def int_area(area):
    import numpy as np
    return np.where(np.array(['A0', 'A1', 'A2', 'B0', 'B1', 'B2'])==area)[0][0]
area_nc.variables['in_temp'][0, int_area('A0')] = 23

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM