gpt4 book ai didi

python - python/netcdf4 中的字符串处理

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:27 25 4
gpt4 key购买 nike

我是 netCDF4 的新手,但我有以下内容:

import netCDF4
nc = netCDF4.Dataset('test.nc','w',format='NETCDF4_CLASSIC')
lat = nc.createVariable('lat','d')
lon = nc.createVariable('lon','d')
place = nc.createVariable('place','c')
lat[:]=17.002
lon[:]=-81.501
#place[:]='test'
nc.close()

我想为变量“place”分配一个超过 1 个字符的值。在不使用属性(例如 place.name='test')的情况下如何做到这一点?

最佳答案

关键是使用 netCDF4.stringtochar将字符串数组转换为字符数组的函数。

import netCDF4
import numpy as np

str_out = netCDF4.stringtochar(np.array(['test'], 'S4'))

nc = netCDF4.Dataset('./test.nc', 'w', format='NETCDF4_CLASSIC')
nc.createDimension('lat', 1)
nc.createDimension('lon', 1)
nc.createDimension('nchar', 4)

lat = nc.createVariable('lat', 'f4', ('lat',))
lon = nc.createVariable('lon', 'f4', ('lon',))
place = nc.createVariable('place', 'S1', ('nchar'))

lat[:] = 17.002
lon[:] = -81.501
place[:] = str_out

nc.close()

你可以检查输出结果

>>> ncks test.nc 
...
lat[0]=17.002
lon[0]=-81.501
nchar[0] place[0--3]='test'

请注意,通过删除“NETCDF4_CLASSIC”的格式,您可以通过另一种方式完成此操作:

str_out = np.array(['test'], dtype='object')

nc = netCDF4.Dataset('./test.nc', 'w')
nc.createDimension('lat', 1)
nc.createDimension('lon', 1)
nc.createDimension('str_dim', 1)

lat = nc.createVariable('lat', 'f4', ('lat',))
lon = nc.createVariable('lon', 'f4', ('lon',))
# Now we can use the data type of 'str'
place = nc.createVariable('place', str, ('str_dim',))

lat[:] = 17.002
lon[:] = -81.501
place[:] = str_out

nc.close()

>>> ncks test.nc
...
lat[0]=17.002
lon[0]=-81.501
str_dim[0] place[0]=test

关于python - python/netcdf4 中的字符串处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37079883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com