【问题标题】:Python: Is there a way to get the average of the n newest numbers in an array?Python:有没有办法获得数组中 n 个最新数字的平均值?
【发布时间】:2019-07-19 11:18:45
【问题描述】:

我正在尝试构建一种电池表,其中我有一个程序可以收集电压样本并将其添加到数组中。我的想法是,当电池充满时我会收集大量数据,然后构建一个函数,将这些数据与最近 100 次左右的电压读数的平均值进行比较,因为每隔几秒就会添加新读数因为我不会打断这个过程。

我正在使用 matplotlib 来显示电压输出,到目前为止它工作正常:I posted an answer here on live changing graphs

电压函数如下所示:

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

【问题讨论】:

标签: python arrays numpy


【解决方案1】:

这是一个相当简单的问题。假设您使用的是 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>)

【讨论】:

    【解决方案2】:

    使用带负索引的切片表示法来获取列表中的最后 n 个项目。

    yar[-100:]
    

    如果切片大于列表,则返回整个列表。

    【讨论】:

      【解决方案3】:

      我认为你甚至不需要使用 numpy。您可以通过对数组进行切片来访问最后 100 个元素,如下所示:

      l = yar[-100:]
      

      这将返回索引从 -100(“第 100 个”最后一个元素)到 -1(最后一个元素)的所有元素。然后,您可以只使用原生 Python 函数,如下所示。

      mean = sum(l) / len(l)
      

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

      【讨论】:

        【解决方案4】:

        您可以使用 Python 标准库 statistics:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-09-22
          • 1970-01-01
          • 2022-11-20
          • 1970-01-01
          • 1970-01-01
          • 2011-04-29
          • 1970-01-01
          相关资源
          最近更新 更多