Search code examples
pythonarraysmeanreshape

How to find the mean and reshape an array in python


I have an array of the shape (901, 201, 3, 20).

Please, how can I find the mean of the third matrix to give me (901, 201, 20) or (901, 201, 1, 20)?


Solution

  • Assuming you are using numpy, this is quite easy using numpy.mean. The first argument would be the array, and as second argument you specify the axis over which to take the mean.

    import numpy as np
    
    a = np.zeros((901, 201, 3, 20))
    b = np.mean(a, axis=2)
    
    print(b.shape) # (901, 201, 20)
    

    I recommend you to take a look at the documentation. You could for example also use the keepdims argument to keep the dimension of the axis, resulting in a shape of (901, 201, 1, 20). Hope this helps