【发布时间】:2021-09-27 07:05:45
【问题描述】:
我正在从许多其他文件创建一个 NetCDF 文件,我唯一的问题是获取一个字符串值并将其写入 NetCDF 变量。现在,下面的代码可以成功写入数据(时间、纬度、经度和其他变量),但它只取我的站列表“S”中的最后一个值。对于变量station。有两种方法可以做到这一点。一种是读取和写入我在下面列出的全局属性站名。我还有一个与相同值匹配的字符串填充列表。我试过在这里搜索,但找不到。也许它在chartostring 和stringtochar 命令中?我在这里与另一个示例一起工作,alebit 没有任何循环。我想我需要额外的代码来确保它写入所有电台名称,而不仅仅是最后一个。
import netCDF4 as nc
import numpy as np
import xarray as xr
# create list of station names for dataset writing (listObsFile is list of all NetCDF files)
S = []
for i in listObsFiles:
if i.endswith('0h2021.nc'):
statID = i[8:13]
S.append(statID)
waveObsNC = nc.Dataset(file, 'w')
nstrings = waveObsNC.createDimension('nstrings', len(S))
nchars = waveObsNC.createDimension('nchars', 5)
station = waveObsNC.createVariable('station', 'S5', ('station',))
v = waveObsNC.createVariable('v', 'S1', ('nchars'))
for i in range(len(S)):
File = xr.open_dataset(filepath+'saveWave'+ str(S[i]) +'h2021.nc')
# Read in station data, deconstruct and rebuild to create valid NetCDF variable
st = File.attrs['station']
datain = np.array([st],dtype='S5')
v[:] = nc.stringtochar(datain1)
station[:] = nc.chartostring(v[:])
# waveObsNC.close()
station[:] 的上述代码的输出:
print(station[:])
array(['51210', '51210', '51210', '51210', '51210', '51210', '51210',
'51210', '51210', '51210', '51210'], dtype=object)
上面的替代方法是st = S[i],它产生相同的站字符串值。以下是该列表:
print(S)
['41010', '41040', '41110', '42060', '42360', '44020', '44030', '44090', '46060', '51000', '51210']
但同样的错误:
print(station[:])
array(['51210', '51210', '51210', '51210', '51210', '51210', '51210',
'51210', '51210', '51210', '51210'], dtype=object)
【问题讨论】:
标签: python string for-loop netcdf python-xarray