I want to extract time series from a NetCDF to csv for a specific location. I got this far with the code but it gives the TypeError: a bytes-like object is required, not 'str'
How can I overcome this issue? Also, will this developed code have as output: time/mwp for the specific location?
import netCDF4
import pandas as pd
import matplotlib.pyplot as plt
import csv
import numpy as np
from netCDF4 import Dataset, num2date
from pylab import *
import xarray
f = netCDF4.Dataset('Wave_period_global.nc')
f.variables.keys()
print (f)
lat = f.variables['latitude'][:]
lon = f.variables['longitude'][:]
time_var = f.variables['time']
dtime = netCDF4.num2date(time_var[:],time_var.units)
mwp = f.variables['mwp'][:]
print(lon.min(), lon.max())
print(lat.min(), lat.max())
longitude = 172
latitude = 50
def near(array,value):
idx=(abs(array-value)).argmin()
return idx
ix = near(lat, latitude)
iy = near(lon, longitude)
print ('Latitude =',ix)
print ('Longitude =',iy)
with open ('Wave_period_global.csv', 'wb') as csvfile:
filewriter = csv.writer(csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for ln in range(len(lon)):
for lt in range(len(lat)):
value=f.variables['mwp'][0][lt][ln]
dtime = netCDF4.num2date(time_var[0],time_var.units)
print(dtime,lat[lt],lon[ln,],value)
filewriter.writerow([dtime,lat[lt],lon[ln,],value])
See my comment above. I'm leaving output as csv out of my answer to focus on your real question.
from netCDF4 import Dataset, num2date
f = netCDF4.Dataset('Wave_period_global.nc')
lat = f.variables['latitude'][:]
lon = f.variables['longitude'][:]
time_var = f.variables['time']
# These are all datetime object.
dtime = netCDF4.num2date(time_var[:],time_var.units)
mwp = f.variables['mwp'][:]
print(lon.min(), lon.max())
print(lat.min(), lat.max())
longitude = 172
latitude = 50
def near(array,value):
idx=(abs(array-value)).argmin()
return idx
ix = near(lat, latitude)
iy = near(lon, longitude)
print ('Latitude =',ix)
print ('lat[] =', lat[ix])
print ('Longitude =',iy)
print ('lon[] =', lon[iy])
for i in range(len(dtime)):
value=f.variables['mwp'][i][ix][iy]
print(dtime[i],lat[ix],lon[iy,],value)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.