0

I'm coming from IDL, so I'm most used to for loops with explicit indicing. I have read about how python does things differently and that you should just be able to say

for thing in things:

What I can't figure out is if a I have a 4 dimensional array and I want to perform an operation in one dimension of the array, how do I save out the result in a 4 dimensional array and do it in the 'python' way.

I have a 4 dimensional array in time, altitude, latitude, longitude. I want to smooth it using a running mean window of N=9.

Here is the code that I am working with:

KMCM_T = g.variables['temperature'][:,:,:,:]      #K
N = 9
T_bar_run = []

for idx, lon in enumerate(KMCM_lon):
    for idy, lat in enumerate(KMCM_lat):
        for idz, lev in enumerate(KMCM_levels):
            T_bar_run[:][idz][idy][idx] = np.convolve(KMCM_T[:,idz,idy,idx], np.ones((N,))/N, mode='same')
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
j_hailglim
  • 41
  • 1
  • 7
  • Possible duplicate of [Convolution along one axis only](https://stackoverflow.com/questions/5228718/convolution-along-one-axis-only) – berkelem Oct 02 '18 at 20:27
  • `T_bar_run[:, idz, idy, idx]` is a better way of indexing a 4 array. – hpaulj Oct 02 '18 at 20:55

1 Answers1

1

In this specific case you could probably use scipy.ndimage.convolve1d:

from scipy.ndimage import convolve1d

T_bar_run = convolve1d(KMCM_T, np.ones(N)/N, axis=0, mode='constant')

The "numpy way of doing things" is avoiding loops because in numerical applications often the overhead of an interpreted loop dwarfs the cost of its payload. This is done by relying on vectorized functions, i.e. functions that apply a certain operation to every cell of its array arguments.

Many such functions act naturally along one or a few dimensions which is why you will frequently encounter the axis keyword argument.

Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
  • Thank you- this worked. I will be reading more about using the "numpy" way of doing things, which sounds like it will end up creating faster code for me. – j_hailglim Oct 02 '18 at 21:38