0

I have an object from netCDF file with the following properties:

float32 zeta(time, y, x)
    long_name: free surface height
    units: meter
unlimited dimensions: time
current shape = (200, 52, 52)
filling off
)

I need to reduce this element by reading every other element from it in Python. I tried by

temp = data.variables['zeta']
zeta_pck = temp[::2].copy()

but it does not work because the output of print zeta_pck.shape is (100,52,52) that is taking the first dimension only

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
Rational Rose
  • 73
  • 1
  • 10

1 Answers1

2

You need to index along all the dimensions:

zeta_pck = data.variables['zeta'][::2, ...]

The Ellipsis object, represented by ... in slice notation, is equivalent to doing : for all remaining dimensions. Another way to write the above is

zeta_pck = data.variables['zeta'][::2, :, :]

The main difference is that the second version only works for 3D arrays, while the first version works for all dimensions, including 1.

If, for some reason you need to subset along all dimensions, do

zeta_pck = data.variables['zeta'][::2, ::2, ::2]

This can be rewritten for an arbitrary number of dimensions using the fact that the index ::2 represents a slice builtin object. You can therefore do

temp = data.variables['zeta']
index = (slice(None, None, 2),) * temp.ndim
zeta_pck = temp[index]

Index here is the same tuple of slices that is witten ::2, ::2, ::2 in the previous version.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264