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
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])