Average positive numbers in a row

前端 未结 2 1451
我在风中等你
我在风中等你 2021-01-23 18:20

I have a numpy matrix, and each row has a combination of positive and negative numbers.

I want to create a new vector, that gives me the average of all the positive numb

相关标签:
2条回答
  • 2021-01-23 18:30

    A possible solution would be

    • select all non-negative
    • compute explicitly the mean as sum/count

    In code:

    notneg = x >= 0
    result = (x * notneg).sum(1) / notneg.sum(1)
    
    0 讨论(0)
  • 2021-01-23 18:34

    If it's guaranteed to have at least one positive number (>=0) per row, you could convert the negative numbers (excluding 0) to NaNs with np.where and then use np.nanmean along the rows, like so -

    np.nanmean(np.where(A>=0,A,np.nan),axis=1)
    

    Sample run -

    In [69]: A
    Out[69]: 
    array([[ 2,  3, -6, -6, -4],
           [-5, -6, -1, -1,  3],
           [-8,  5, -7, -9, -9],
           [-3,  0,  7, -5, -6]])
    
    In [70]: np.nanmean(np.where(A>=0,A,np.nan),axis=1)
    Out[70]: array([ 2.5,  3. ,  5. ,  3.5])
    
    0 讨论(0)
提交回复
热议问题