average of a number of arrays with numpy without considering zero values

前端 未结 1 2032
借酒劲吻你
借酒劲吻你 2021-01-06 06:27

I am working on numpy and I have a number of arrays with the same size and shape like: a= [153 186 0 258] b=[156 136 156 0] c=[193 150 950 757] I want to ha

相关标签:
1条回答
  • 2021-01-06 07:22

    In Python:

    >>> a = [153, 186, 0, 258]
    >>> b = [156, 136, 156, 0]
    >>> c = [193, 150, 950, 757]
    >>> import statistics
    >>> [statistics.mean([x for x in s if x]) for s in zip(*[a, b, c])]
    [167.33333333333334, 157.33333333333334, 553, 507.5]
    

    In numpy:

    >>> import numpy as np
    >>> A = np.vstack([a,b,c])
    >>> np.average(A, axis=0, weights=A.astype(bool))
    array([ 167.33333333,  157.33333333,  553.        ,  507.5       ])
    

    If there is a possibility that all values in a column can equal zero, you may want to use masked arrays to avoid the problem that the normalization is impossible (weights can't sum to zero). Undefined slots in output will be masked.

    >>> a[0] = b[0] = c[0] = 0
    >>> A = np.vstack([a,b,c])
    >>> np.ma.average(A, axis=0, weights=A.astype(bool))
    masked_array(data=[--, 157.33333333333334, 553.0, 507.5],
                 mask=[ True, False, False, False],
                 fill_value=1e+20)
    >>> np.ma.average(A, axis=0, weights=A.astype(bool)).tolist()
    [None, 157.33333333333334, 553.0, 507.5]
    
    0 讨论(0)
提交回复
热议问题