0

I have a daily netcdf data containing a point data of single lat and lon. The shape of vairable (var.shape) is ('time', 'z'), here z is depths in ocean. I want to select and plot a varaible within a specified date range (2019-01-01 to 2020-12-31) and also range of depths (100 to 1500). I know how to select the depth range, but couldn't do the same for time. How can I choose a range of time?

I tried the following code, but the indexing of time didn't work here

import warnings
warnings.filterwarnings('ignore')

import os
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
import matplotlib as mpl

path_in = "./"
file_ds = xr.open_dataset(path_in + 'ocean.nc')

lon = file_ds.variables['lon'][:]
lat = file_ds.variables['lat'][:]
li = file_ds.variables['depth'][0,:,0,0] 
time = file_ds.variables['time'][:]
var = file_ds.variables['var'][:,:,0,0]

index = np.intersect1d(np.where(li<-100),np.where(li>=-1500))
tindex = np.intersect1d(np.where(time<(['2020-01-01'],dtype='datetime64[ns]'),np.where(time>=['2020-12-31'],dtype='datetime64[ns]'))

var_100_1500 = var[tindex,index] 

fig, ax = plt.subplots(figsize=(15, 9))
fillprof = ax.contourf(time[tindex],li[index],var_100_1500.T,levels=40)

clb=plt.colorbar(fillprof, orientation="vertical", pad=0.02)
clb.ax.tick_params(labelsize=18) 

The error while ploting is as below

  tindex = np.intersect1d(np.where(time<(['2020-01-01'],dtype='datetime64[ns]'),np.where(time>=['2020-12-31'],dtype='datetime64[ns]'))
                                                               ^
SyntaxError: invalid syntax

Can anyone give me a solution?

  • what do you mean it didn't work? can you provide a traceback? – Michael Delgado Jun 22 '22 at 16:45
  • It is a syntax error with 'tindex'. ```tindex = np.intersect1d(np.where(time<(['2020-01-01'],dtype='datetime64[ns]'),np.where(time>=['2020-12-31'],dtype='datetime64[ns]')) ^ SyntaxError: invalid syntax ``` – linux_lover Jun 22 '22 at 16:49
  • Can you edit your question to include the code which generates the error and the [full traceback](//realpython.com/python-traceback)? See the guide to [ask] – Michael Delgado Jun 22 '22 at 17:19
  • Generally though a syntax error just means you have a typo leading to invalid python. So this isn’t an xarray problem - it’s something like an extra parenthesis, comma, quote etc. – Michael Delgado Jun 22 '22 at 17:20
  • By my count you don’t close all your parens – Michael Delgado Jun 22 '22 at 17:21

1 Answers1

1

Your are missing a ")" at the end of the tindex assignment line.

It should look like this:

tindex = np.intersect1d(np.where(time<(['2020-01-01'], dtype='datetime64[ns]'), np.where(time>=['2020-12-31'], dtype='datetime64[ns]')))