Search code examples
pythonvectorizationmeannumpy-ndarrayarray-broadcasting

Taking mean of numpy arrays of different lengths within another numpy array without using for loop


I have a 2d array that contains other arrays but the arrays are of different sizes. I want to find the mean of each individual array that is contained in that 2d array without using a loop.

I want to take the mean of array_combined in the code below.

import numpy as np
array1=np.array([1,2,3,4,5])
array2=np.array([1,2,3])
array3=np.array([1,2,3,4,5])
list_combined = [array1,array2,array3]
array_combined = np.array(list_combined)

Solution

  • This should solve your problem:

    import numpy as np
    array1=np.array([1,2,3,4,5])
    array2=np.array([1,2,3])
    array3=np.array([1,2,3,4,5])
    list_combined = [array1,array2,array3]
    array_combined = np.array(list_combined)
    
    mean_sub_arrays = np.vectorize(np.mean)(array_combined)
    

    Ran it on Google Colab to verify and attached screenshot.1

    Copied from solution provided by @vielkind on this link: Average of elements in a subarray