Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading