对于向NetCDF变量添加字符串列表的循环,仅添加最后一个值

2024-09-28 23:41:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从许多其他文件创建一个NetCDF文件,唯一的问题是获取一个字符串值并将其写入NetCDF变量。现在,下面的代码可以成功地写入数据(time、lat、lon和其他变量),但它只获取我的站点列表“S”中的最后一个值。对于变量station。有两种方法可以做到这一点。一个是读取和写入我在下面列出的全局属性站点名称。我还有一个与相同值匹配的字符串填充列表。我试着在这里搜索,但找不到。可能是在chartostringstringtochar命令中?我在这里用另一个例子,没有任何循环的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)

Tags: 字符串代码inimport列表forasnetcdf
1条回答
网友
1楼 · 发布于 2024-09-28 23:41:18

原来我想得太多了。如果我正在读取列表S中的字符串列表,那么是的,我需要执行stringtocharchartostring来解构并创建VLEN字符串变量值。但是,如果从全局属性station name中获取station name,则意味着它显然是一个已在NetCDF文件中使用的格式正确的字符串。因此,在循环中,使用i索引station变量并将其与属性station name相等非常有效,即:

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
     station[i] = File.attrs['station']

相关问题 更多 >