I am trying to convert a CSV file to netCDF4 through Python, but I find it hard to understand how I can store information from the .csv table format to netCDF. My main problem is how to declare variables from columns to netCDF4 working format? Everything that I found usually extracts information from netCDF4 in .csv or ASCII. I presented sample data, code sample, and my errors for declaring corresponding arrays. Any help would be greatly appreciated.
The following is an example table below:
Station Name Country Code Lat Lon mn.yr temp1 temp2 temp3 hpa
Somewhere US 12340 35.52 23.358 1.19 -8.3 -13.1 -5 69.5
Somewhere US 12340 2.1971 -10.7 -13.9 -7.9 27.9
Somewhere US 12340 3.1971 -8.4 -13 -4.3 90.8
My sample code is:
#! / usr / bin / env python
import scipy
import numpy
import netCDF4
import csv
from numpy import arange, dtype
#Declare empty arrays
v1 = []
v2 = []
v3 = []
v4 = []
# Open the csv file and declare a variable for arrays for each header
f = open('station_data.csv', 'r').readlines()
for line in f[1:]:
fields = line.split(',')
v1.append(fields[0])
v2.append(fields[1])
v3.append(int(fields[2]))
v4.append(float(fields[3]))
v5.append(float(fields[3]))
print v1
print v2
print v3
print v4
#convert to netcdf4 framework, which works like netcdf
ncout = netCDF4.Dataset('station_data.nc','w')
# latitude and longitude. Enable NaN for Missing Numbers
lats_out = -25.0 + 5.0*arange(v4,dtype='float32')
lons_out = -125.0 + 5.0*arange(v5,dtype='float32')
# output.
press_out = 900. + arange(v4*v5,dtype='float32') # 1d array
press_out.shape = (v4,v5) # reshape to 2d array
temp_out = 9. + 0.25*arange(v4*v5,dtype='float32') # 1d array
temp_out.shape = (v4,v5) # reshape to 2d array
# create lat and lon sizes.
ncout.createDimension('latitude',v4)
ncout.createDimension('longitude',v5)
# .
lats = ncout.createVariable('latitude',dtype('float32').char,('latitude',))
lons = ncout.createVariable('longitude',dtype('float32').char,('longitude',))
# var. , .
lats.units = 'degrees_north'
lons.units = 'degrees_east'
# vars.
lats[:] = lats_out
lons[:] = lons_out
#
press = ncout.createVariable('pressure',dtype('float32').char,('latitude','longitude'))
temp = ncout.createVariable('temperature',dtype('float32').char,'latitude','longitude'))
# .
press.units = 'hPa'
temp.units = 'celsius'
# .
press[:] = press_out
temp[:] = temp_out
ncout.close()
f.close()
:
Traceback (most recent call last):
File "station_data.py", line 33, in <module>
v4.append(float(fields[3]))
ValueError: could not convert string to float: