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)
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
Kuo-Hsien Chang
  • 925
  • 17
  • 40

3 Answers3

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.

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
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)
tom10
  • 67,082
  • 10
  • 127
  • 137
  • 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. – Kuo-Hsien Chang Nov 14 '17 at 18:22
  • 1
    `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. – Brad Solomon Nov 14 '17 at 18:38
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.

etaloof
  • 642
  • 9
  • 21