0

A sensor generates an reading every one second for five seconds. I was trying to use the function np.mean to calculate the average of five sensor readings (i.e., sensor1_t1 to sensor1_t5), however it doesn't work.

Can you please help me on this?

Thanks.

sensor1_t1 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t2 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t3 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t4 = BridgeValue(0) * 274.0 - 2.1
sleep(1)
sensor1_t5 = BridgeValue(0) * 274.0 - 2.1
sleep(1)

# my code - not working
#avg_sensor1 = np.mean(sensor1_t1, sensor1_t2, sensor1_t3, sensor1_t4, sensor1_t5)

3 Answers 3

3

You need to pass an array-like object to the a parameter of np.mean. Try:

avg_sensor1 = np.mean([sensor1_t1, sensor1_t2, sensor1_t3, sensor1_t4, sensor1_t5])

You're currently passing 5 arguments when you need to pass them as one array-like object.

In other words, the syntax for np.mean is:

numpy.mean(a, axis=None, dtype=None, out=None, ...

The way you currently are calling the function, you're passing 5 positional arguments. These get interpreted as separate parameters:

  • sensor1_t1 is passed to a
  • sensor1_t2 is passed to axis
  • sensor1_t3 is passed to dtype

...and so on.

Note that the syntax I suggested passes a list, which is one of the structures that's considered "array-like." More on that here if you are interested.

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

Comments

2

This would be more easily done using Numpy arrays throughout. Something like:

import numpy as np

N = 5
sensor1 = np.zeros((N,), dtype=float)

for i in range(N):
    sensor1[i] = BridgeValue(0) * 274.0 - 2.1
    sleep(1)

average = np.mean(sensor1)

2 Comments

I was thinking about using np.empty based on what I learned from others. Could you please explain why you are using np.zeros? I am assuming the (N,) is appending new entries to the array?! Thx.
np.zeros((N,) creates an array of zeros, with length N. (Technically a 1d array.) Then you modify each value within the loop. So when i=1, you are assigning BridgeValue(0) * 274.0 - 2.1 to sensor[1] (the 2nd entry in the array, because it is 0-indexed). So, you could use np.empty or np.zeros; they both function just as placeholders.
0

Because numpy is mainly used with arrays (especially numpy.ndarray) numpy.mean expects an array as it's first argument. But you don't need to create an ndarray you can simply change np.mean(sensor1_t1, sensor1_t2, sensor1_t3, sensor1_t4, sensor1_t5) to np.mean([sensor1_t1, sensor1_t2, sensor1_t3, sensor1_t4, sensor1_t5]) and numpy will take care of the rest.

Comments

Your Answer

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.