Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String handling in python/netcdf4

Tags:

python

netcdf

I am new to netCDF4 but I have the following:

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. how do you do it without using attributes (e.g. place.name='test')?

like image 448
Gayans Avatar asked Mar 12 '23 09:03

Gayans


1 Answers

The key is to use the netCDF4.stringtochar function to convert a string array to a character array.

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:

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 
like image 165
N1B4 Avatar answered Mar 25 '23 01:03

N1B4