numpy.mean on varying row size

前端 未结 1 1260
时光说笑
时光说笑 2020-12-21 05:52

The numpy mean function works perfectly fine when the dimensions are the same.

a = np.array([[1, 2], [3, 4]])
a.mean(axis=1)
array([ 1.5,  3.5])
相关标签:
1条回答
  • 2020-12-21 06:36

    Here's an approach -

    # Store length of each subarray
    lens = np.array(map(len,a))
    
    # Generate IDs based on the lengths
    IDs = np.repeat(np.arange(len(lens)),lens)
    
    # Use IDs to do bin-based summing of a elems and divide by subarray lengths
    out = np.bincount(IDs,np.concatenate(a))/lens
    

    Sample run -

    In [34]: a   # Input array
    Out[34]: array([[1, 2], [3, 4, 5]], dtype=object)
    
    In [35]: lens = np.array(map(len,a))
        ...: IDs = np.repeat(np.arange(len(lens)),lens)
        ...: out = np.bincount(IDs,np.concatenate(a))/lens
        ...: 
    
    In [36]: out  # Average output
    Out[36]: array([ 1.5,  4. ])
    

    Simpler alternative way using list comprehension -

    In [38]: [np.mean(i) for i in a]
    Out[38]: [1.5, 4.0]
    
    0 讨论(0)
提交回复
热议问题