Reputation: 41
I was given code and I'm familiar with numpy, but this one line really has me stuck looking for an answer.
plt.contourf(lat,lev,T.mean(0).mean(-1),extend='both')
T is a 4 dimensional variable dependent on time, lat, lon, lev.
My question is, what does the T.mean(0).mean(-1)
do?
Thanks!
Upvotes: 0
Views: 1228
Reputation: 54340
Here are some examples, which I hope will explain what is going on:
In [191]:
#the data
a=np.random.random((3,3,3))
print a
[[[ 0.21715561 0.23384392 0.21248607]
[ 0.10788638 0.61387072 0.56579586]
[ 0.6027137 0.77929822 0.80993495]]
[[ 0.36330373 0.26790271 0.79011397]
[ 0.01571846 0.99187387 0.1301911 ]
[ 0.18856381 0.09577381 0.03728304]]
[[ 0.18849473 0.16550599 0.41999887]
[ 0.65009076 0.39260551 0.92284577]
[ 0.92642505 0.46513472 0.77273484]]]
In [192]:
#mean() returns the grand mean
a.mean()
Out[192]:
0.44176096869094533
In [193]:
#mean(0) returns the mean along the 1st axis
a.mean(0)
Out[193]:
array([[ 0.25631803, 0.22241754, 0.47419964],
[ 0.25789853, 0.6661167 , 0.53961091],
[ 0.57256752, 0.44673558, 0.53998427]])
In [195]:
#what is this doing?
a.mean(-1)
Out[195]:
array([[ 0.22116187, 0.42918432, 0.73064896],
[ 0.47377347, 0.37926114, 0.10720688],
[ 0.25799986, 0.65518068, 0.72143154]])
In [196]:
#it is returning the mean along the last axis, in this case, the 3rd axis
a.mean(2)
Out[196]:
array([[ 0.22116187, 0.42918432, 0.73064896],
[ 0.47377347, 0.37926114, 0.10720688],
[ 0.25799986, 0.65518068, 0.72143154]])
In [197]:
#Ok, this is now clear: calculate the mean along the 1st axis first, then calculate the mean along the last axis of the resultant.
a.mean(0).mean(-1)
Out[197]:
array([ 0.31764507, 0.48787538, 0.51976246])
IMO, using T
as a variable name is probably not a good idea. .T()
means transpose in numpy
.
Upvotes: 2
Reputation: 396
It's the axis along which to take the mean.
>>> import numpy
>>> arr = numpy.array([[1,2,3,4],[5,6,7,8]])
>>> arr.mean(0) == [(1+5)/2, (2+6)/2, (3+7)/2, (4+8)/2]
array([ True, True, True, True], dtype=bool)
>>> arr.mean(1) == [(1+2+3+4)/4, (5+6+7+8)/4]
array([ True, True], dtype=bool)
Upvotes: 2
Reputation: 1396
The value passed to mean specifies the axis along which to take the mean. Therefore, T.mean(0) takes the mean along the 0th axis and returns a 3D array. The .mean(-1) then performs the mean along the last axis of the newly created 3D array, returning a 2D array.
Which is conveniently ideal for contourf.
Upvotes: 4