簡體   English   中英

Python:有沒有辦法獲取數組中n個最新數字的平均值?

[英]Python: Is there a way to get the average of the n newest numbers in an array?

我正在嘗試構建一種電池電量計,其中有一個程序可以收集電壓樣本並將其添加到陣列中。 我的想法是,當電池充滿時,我會收集大量數據,然后構建一個函數,將這些數據與最近100次左右的電壓讀數的平均值進行比較,因為每隔幾秒鍾就會添加一次新的讀數因為我不會打擾這個過程。

我正在使用matplotlib來顯示電壓輸出,到目前為止它工作正常: 我在實時變化圖上發布了答案

電壓功能如下所示:

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)))

我只是想知道獲取數組的最后x個數字的平均值的語法應該是什么樣的?

if len(yar) > 100
    #get average of last 100 values only

使用帶有負索引的切片符號可獲取列表中的n個最后一項。

yar[-100:]

如果切片大於列表,則將返回整個列表。

這是一個相當簡單的問題。 假設您正在使用numpy,它提供了簡單的求平均值功能。

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

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

如果要將常規數組轉換為numpy數組,可以使用以下方法:

np.array(<your-array-goes-here>)

我認為您甚至不需要使用numpy。 您可以通過如下切割數組來訪問最后100個元素:

l = yar[-100:]

這將返回索引處從-100(最后一個元素“第100個”)到-1(最后一個元素)的所有元素。 然后,您可以按照以下方式使用本機Python函數。

mean = sum(l) / len(l)

Sum(x)返回列表中所有值的總和,len(l)返回列表的長度。

您可以使用Python標准庫統計信息

import statistics

statistics.mean(your_data_list[-n:])  # n = n newst numbers

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM