Average positive numbers in a row

前端 未结 2 1450
我在风中等你
我在风中等你 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: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])
    

提交回复
热议问题