Reputation: 935
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)
Upvotes: 0
Views: 417
Reputation: 69172
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)
Upvotes: 2
Reputation: 40878
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.
Upvotes: 3
Reputation: 662
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.
Upvotes: 0