如何在不导入外部模块(matplotlib 除外)的情况下绘制 运行 平均值?

How does one plot a running average without importing external modules (other than matplotlib)?

这里是 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,而我试图在没有外部导入的情况下进行操作(上述例外情况除外)。

需要平滑的噪声数据

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 window 尺码 n

n = 3

每个window可以表示一个切片

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)

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


也许您可以导入一个 internal/built-in 模块并使用这个 SO 答案 -


大量搜索 running average algorithm python