# Best practices with multidimensional arrays: How to specify the axis?

In numpy, all basic operations can be applied to a specific axis of a given input array, like so:

np.average(an_array,axis=3)


in Mathematica however all functions are always applied to the first dimension apparently:

Dimensions[AnArray]
Dimensions[Mean[AnArray]]


{40, 2, 61, 3}

{2, 61, 3}

When I want to average the third axis I then do:

Dimensions[AnArray]
Dimensions[Transpose[Mean[Transpose[AnArray, {3, 2, 1, 4}]], {2, 1, 3}]]


{40, 2, 61, 3}

{40, 2, 3}

This is very cumbersome. Is there an easier way in Mathematica?

• Map takes a level specification. E.g. [Transpose[Mean[Transpose[AnArray, {3, 2, 1, 4}]], {2, 1, 3}] can be written: Map[Mean, AnArray, {2}] – Daniel Huber Feb 11 at 17:01

SeedRandom
anArray = RandomInteger[10, {40, 2, 61, 3}];

meana = Transpose[Mean[Transpose[anArray, {3, 2, 1, 4}]], {2, 1, 3}];
Dimensions[meana]
{40, 2, 3}

axis = 3;


1. Map Mean at level axis - 1:

meanb =  Map[Mean, anArray, {axis - 1}]
Dimensions[meanb]

{40, 2, 3}


2. Flatten with {axis} as the second argument and take Mean:

meanc = Mean @ Flatten[anArray, {axis}];
Dimensions[meanc]

{40, 2, 3}

meana == meanb == meanc

True


For the Mean example, you can use Total instead, which does support other dimensions:

A = RandomInteger[10, {40, 2, 61, 3}];

r1 = Transpose[Mean[Transpose[A, {3, 2, 1, 4}]], {2, 1, 3}];
r2 = Total[A, {3}]/Dimensions[A][];

r1 === r2


True

• How about other functions? Norm e.g.? – Mr Puh Feb 11 at 16:58