Home > Net >  How to get the average of only positive numbers in a numpy array?
How to get the average of only positive numbers in a numpy array?

Time:02-22

We were given two text files that contain numbers and we need to load them using numpy.loadtxt and then find the mean of only the positive numbers within the text files.

This is what I've tried so far:

A = np.loadtxt('A.txt')
B = np.loadtxt('B.txt')
A_mean = np.mean(np.where(A>0))
B_mean = np.mean(np.where(B>0))
print(f'A={A_mean}')
print(f'B={B_mean}')

I know this is obviously wrong since it appears to be returning the average of the index numbers, not the values. How can I get the average of the actual values?

CodePudding user response:

np.where(A > 0) returns the indices where A > 0 as you noticed. To get the elements of A, use the indices: np.mean(A[np.where(A > 0)]).

But wait, A > 0 is a boolean array that has True in every element that meets the condition and False elsewhere. Such an array is called a "mask", and can be used for indexing as well:

A[A > 0].mean()
  • Related