【问题标题】:How does one plot a running average without importing external modules (other than matplotlib)?如何在不导入外部模块(matplotlib 除外)的情况下绘制运行平均值?
【发布时间】:2017-01-01 00:55:53
【问题描述】:

这是一个link to the file,其中包含“sunspots.txt”中的信息。除了外部模块 matploblib.pyplot 和 seaborn 之外,如何在不导入 numpy 和 future 等外部模块的情况下计算运行平均值? (如果有帮助,我可以在没有 numpy 的情况下使用 linspace 和 loadtxt。)

如果有帮助,我的代码发布在下面:

## open/read file
f2 =     open("/Users/location/sublocation/sunspots.txt", 'r')
## extract data
lines = f2.readlines()
## close file
f2.close()

t = [] ## time
n = [] ## number
## col 1 == col[0] -- number identifying which month
## col 2 == col[1] -- number of sunspots observed
for col in lines: ## 'col' can be replaced by 'line' iff change below is made
    new_data = col.split() ## 'col' can be replaced by 'line' iff change above is made
    t.append(float(new_data[0]))
    n.append(float(new_data[1]))
## extract data ++ close file

## check ##
# print(t)
# print(n)
## check ##

## import
import matplotlib.pyplot as plt
import seaborn as sns

## plot
sns.set_style('ticks')
plt.figure(figsize=(12,6))
plt.plot(t,n, label='Number of sunspots oberved monthly' )
plt.xlabel('Time')
plt.ylabel('Number of Sunspots Observed')
plt.legend(loc='best')
plt.tight_layout()
plt.savefig("/Users/location/sublocation/filename.png", dpi=600)

问题来自the weblink from this university(PDF 第 11 页,本书第 98 页,练习 3-1)。

在将其标记为重复之前:

similar question was posted here。不同之处在于,所有发布的答案都需要导入外部模块,如 numpy 和 future,而我试图不使用外部导入(上述例外情况除外)。

【问题讨论】:

  • 有多个“移动平均线”。您具体指的是哪一个,具有什么权重和时间窗口? (我们不必查看您的外部链接,但看起来 11 次测量以当前测量为中心,权重相同。)
  • 是的,它是 11 次测量(-5 到 5)。如果有帮助,这里是picture of the problem
  • matplotlib 不需要 numpy 吗?
  • 迭代n个长度的数据切片;得到每个切片的平均值;将平均值保存在另一个列表中;绘制平均值。
  • @wwii 使用 matplotlib 不需要 numpy。 numpy 确实有一个 linspace 函数,但如果可能的话,我更喜欢自己编写代码而不导入。因此,我可以执行以下操作,而不是从 numpy 导入 linspace:'def linspace(lower,upper,length):''return [lower + x*(upper-lower)/length for x in range(length)]'' Ubound = 5' 'Lbound = -5' 'R = linspace( Ubound, Lbound - 1, abs(Ubound - Lbound) + 1 ) ## +-1 因为不包括在内 # # print(R)' (你能详细说明一下吗?你的答案很少?)

标签: python moving-average


【解决方案1】:

需要平滑的噪声数据

y = [1.0016, 0.95646, 1.03544, 1.04559, 1.0232,
     1.06406, 1.05127, 0.93961, 1.02775, 0.96807,
     1.00221, 1.07808, 1.03371, 1.05547, 1.04498,
     1.03607, 1.01333, 0.943, 0.97663, 1.02639]

尝试running average,窗口大小为n

n = 3

每个窗口都可以用切片表示

window = y[i:i+n]

需要一些东西来存储平均值

averages = []

迭代n个长度的数据切片;得到每个切片的平均值;将平均值保存在另一个列表中。

from __future__ import division  # For Python 2
for i in range(len(y) - n):
    window = y[i:i+n]
    avg = sum(window) / n
    print(window, avg)
    averages.append(avg)

当您绘制平均值时,您会发现平均值少于数据中的样本数。


也许您可以导入一个内部/内置模块并使用这个 SO 答案 -https://stackoverflow.com/a/14884062/2823755


大量使用running average algorithm python 搜索的命中

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 2012-12-07
    • 2013-08-22
    • 2010-10-24
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    相关资源
    最近更新 更多