[英]String handling in python/netcdf4
I am new to netCDF4
but I have the following:我是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()
I want to assign the variable 'place' with a value that is more than 1 character.我想为变量“place”分配一个大于 1 个字符的值。 how do you do it without using attributes (eg place.name='test'
)?如果不使用属性(例如place.name='test'
),你如何做到这一点?
The key is to use the netCDF4.stringtochar function to convert a string array to a character array.关键是使用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()
You can check the output with您可以检查输出
>>> ncks test.nc
...
lat[0]=17.002
lon[0]=-81.501
nchar[0] place[0--3]='test'
Note that by removing the format of 'NETCDF4_CLASSIC', you can accomplish this another way:请注意,通过删除“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
For a longer texts, based on the useful answer of N1B4, you can do:对于较长的文本,基于 N1B4 的有用答案,您可以执行以下操作:
from __future__ import print_function
import netCDF4 as nc
import numpy as np
message = """This message is spread over two lines.
I won't even bother counting the characters."""
fname = './test.nc'
# Write the message
with nc.Dataset(fname, 'w') as ds:
ds.createDimension('nchar', len(message))
data = ds.createVariable('message', 'S1', ('nchar'))
data[:] = nc.stringtochar(np.array([message], 'S'))
# Read the message
with nc.Dataset(fname, 'r') as ds:
reconstructed = ds.variables['message'][...].tostring().decode()
print(reconstructed)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.