0

I am trying to build a sort of a battery meter, where I have one program that collects voltage samples and adds it to an array. My idea is, that I collect a lot of data when the battery is full, and then build a function that will compare this data with the average of the last 100 or so readings of the voltage as new readings are added every few seconds as long as I don't interrupt the process.

I am using matplotlib to show the voltage output and so far it is working fine: I posted an answer here on live changing graphs

The voltage function looks like this:

pullData = open("dynamicgraph.txt","r").read() //values are stored here in another function
    dataArray = pullData.split('\n')
    xar = []
    yar = []

    averagevoltage = 0
    for eachLine in dataArray:
        if len(eachLine)>=19:
            x,y = eachLine.split(',')
            xar.append(np.int64(x)) //a datetime value
            yar.append(float(y))    //the reading 
    ax1.clear()
    ax1.plot(xar,yar)
    ax1.set_ylim(ymin=25,ymax=29)
    if len(yar) > 1:
        plt.title("Voltage: " + str(yar [-1]) + " Average voltage: "+ str(np.mean(yar)))

I am just wondering what the syntax of getting the average of the last x numbers of the array should look like?

if len(yar) > 100
    #get average of last 100 values only
  • 1
    numpy.average ? https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.average.html#numpy.average – Jona Jul 19 '19 at 11:22
  • 3
    you can take the last 100 items of an array by doing `yar[-100:]`. You can then get the mean of this by doing `np.mean(yar[-100:])`. – amdex Jul 19 '19 at 11:26
  • Oh it was really so easy, I even had that annotation `str(yar [-1])` there. Thanks! – I_Literally_Cannot Jul 19 '19 at 12:22

4 Answers4

2

Use slice notation with negative index to get the n last items in a list.

yar[-100:]

If the slice is larger than the list, the entire list will be returned.

Håken Lid
  • 22,318
  • 9
  • 52
  • 67
2

It's a rather simple problem. Assuming you're using numpy which provides easy functions for averaging.

array = np.random.rand(200, 1)

last100 = array[-100:]  # Retrieve last 100 entries
print(np.average(last100))  # Get the average of them

If you want to cast your normal array to a numpy array you can do it with:

np.array(<your-array-goes-here>)
Steven
  • 170
  • 3
  • 10
0

I don't think you even need to use numpy. You can access the last 100 elements by slicing your array as follows:

l = yar[-100:]

This returns all elements at indices from -100 ('100th' last element) to -1 (last element). Then, you can just native Python functions as follows.

mean = sum(l) / len(l)

Sum(x) returns the sum of all values within the list, and len(l) returns the length of the list.

0

you could use the Python Standard Library statistics:

import statistics

statistics.mean(your_data_list[-n:])  # n = n newst numbers
kederrac
  • 16,819
  • 6
  • 32
  • 55