【发布时间】: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