Skip to main content
  1. About
  2. For Teams
Asked
Viewed 22k times
1

I want to calculate means and averages in a data set, but for many reasons that I can't go into here, my array contains my values and some "filler" values (which are currently set to -1000).

How can I calculate the mean (for example) on only the non -1000 values?

res=[-1000 for x in range(0,10)]
res[1]=2
res[5]=3
res[7]=4
#something like this?
np.mean(res>-1000)

#the result should be the mean value of 2,3 and 4 (3)

MVCE

res=[1.0, 1.0, 1.0, 1.0, 1.0, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000]
#for instance
print(np.mean(res[res > -1000]))

2 Answers 2

3

Since you tagged numpy, you should use it for indexing / slicing. Here's an example:

res = np.array([-1000 for x in range(0,10)])
res[1]=2
res[5]=3
res[7]=4

output = np.mean(res[res > -1000])  # 3.0

Read the numpy docs for more details on indexing logic.

Sign up to request clarification or add additional context in comments.

5 Comments

as is I get this error "TypeError: unorderable types: list() > int()" but I'll read up on the doc
@JessicaChambers, I'm not sure. Did you copy / paste the above code exactly? You might also want to supply a minimal reproducible example of your problem.
when I copy it exactly it works, as soon as I put it in my code it throws that error... does the list being full of floats (not ints) make a difference? Otherwise there should be no difference... I will add a MCVE to the original post, just to be sure
@JessicaChambers, No, int vs float makes no difference.
@JessicaChambers, In your example, you need to convert your object to an array first: res = np.array(res)
2

Why use another library when you have your friend filter method

import statistics
number_list = [2, -1000, 3, 4, -1000, -1000]
not_1000 = list(filter(lambda x: x != -1000, number_list))
not_1000_mean = statistics.mean(not_1000)

Comments

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.