Python 最多3 个值,平均值和绘图

Python max. 3 values, average and ploting

我是 Python 的新人,我正在处理那个问题,但我遇到了很多错误。 首先,我有 3 个 excel 个文件,我需要从每个 excel 中找到最高的 3 个值。然后,我需要取每 3 个最高值的平均值。之后,我需要绘制平均值,excels 的名称必须在 Y 轴上,平均值必须在 X 轴上。

我有最大值和平均值没有任何错误,但我需要相互联系并得到图表。我写了那些代码,但它没有用。我该如何修复错误? 谢谢。

import numpy as np
import xlrd
book = xlrd.open_workbook("inc.xlsx")
sheet = book.sheet_by_index(0)

def inc_follow_up():
  col = 1
  return max(sheet.col_values(col, start_rowx=2, end_rowx=1441)[:3])

def inc_avg():
    sum(inc_follow_up()) / len(inc_follow_up())

import xlrd
book = xlrd.open_workbook('mok.xlsx')
sheet = book.sheet_by_index(0)

def mok_follow_up():
  col = 1
  return max(sheet.col_values(col, start_rowx=2, end_rowx=1441)[:3])

def mok_avg():
    sum(mok_follow_up()) / len(mok_follow_up())

import xlrd
book = xlrd.open_workbook('sok.xlsx')
sheet = book.sheet_by_index(0)

def sok_follow_up():
  col = 1
  return max(sheet.col_values(col, start_rowx=2, end_rowx=1441)[:3])

def sok_avg():
    sum(sok_follow_up()) / len(sok_follow_up())


plt.plot(inc_avg["Significant wave height (cm)"],inc, color='green', label="Inc")
plt.plot(mok_avg["Significant wave height (cm)"], mok, color='green', label="Mok")
plt.plot(sok_avg["Significant wave height (cm)"], sok, color='green', label="Sok")
plt.title("Free")
plt.ylabel("Significant wave height (cm)")
plt.xlabel("inc","mok","sok")
plt.legend()
plt.show()

问题:

所以我想我现在明白你想做什么,我会尽力解决你的小问题。但是正如我所看到的,您的小代码摘录充满了次要和主要的缺陷,您将需要更加熟悉 python 的基础知识,否则您将随时遇到问题。但稍后会更多...这是我的 "solution"(希望它有效):

首先将所有导入语句放在脚本的顶部(某些例外情况除外)并实际将 matplotlib 导入为 plt:

import numpy as np
import matplotlib.pyplot as plt
import xlrd

那么您似乎想要一个函数,该函数 returns 您可以从某个列表中获取一些最大值。让我们这样做:

def nLargest(ls, n):
    '''return the n largest entries in ls'''
    return list(reversed(sorted(ls)[-n:]))

上面的这个函数有两个参数:列表和应该返回的最大值的数量。它首先使用 "sorted(ls)"(从最低到最高)对数据进行排序,并使用“[-n:]”获取最后的 "n" 个元素。 然后将列表反转(从最高到最低)并返回。

现在只需定义一些值、加载数据并计算您想要的值:

sheetIndex = 0
col = 1
start = 2
end = 1441

book = xlrd.open_workbook("inc.xlsx")
sheet = book.sheet_by_index(sheetIndex)
incData = sheet.col_values(col, start_rowx=start, end_rowx=end)

book = xlrd.open_workbook('mok.xlsx')
sheet = book.sheet_by_index(sheetIndex)
mokData = sheet.col_values(col, start_rowx=start, end_rowx=end)

book = xlrd.open_workbook('sok.xlsx')
sheet = book.sheet_by_index(sheetIndex)
sokData = sheet.col_values(col, start_rowx=start, end_rowx=end)

averages = [np.average(nLargest(incData, 3)), # use numpy for averaging
            np.average(nLargest(mokData, 3)),
            np.average(nLargest(sokData, 3))]

最后按照您想要的方式绘制它:

vals = [1., 2., 3.]
plt.plot(vals, averages)

plt.xticks(vals, ["inc","mok","sok"])
plt.title("Free")
plt.ylabel("Significant wave height (cm)")
plt.xlabel("source files")
plt.show()

所有其他问题
现在我想花点时间看看你的原始代码,我会批评我喜欢的地方:

def follow_up():
    col = 1
    return max(sheet.col_values(col, start_rowx=2, end_rowx=1441)[:3])

老实说,这个函数(以及大多数其他函数)让我非常畏缩……你不应该改变或真正访问函数内的全局变量。函数调用本身应该包含函数所需的大部分数据(或至少包含获取数据所需的所有信息)。您编写了两倍于三个函数,这些函数本质上在不同的数据集上执行相同的操作。虽然这就是函数的用途,但您应该只编写一个函数并将其用于所有数据,有点像这样:

def follow_up(sheet, col, start, end, n):
   '''This function will still not work but at least it's a function...'''
   return max(sheet.col_values(col, start_rowx=start, end_rowx=end)[:n])

那么你在多次执行 "import xlrd"。没必要。 您的策划还需要再看一眼。在实际使用它们之前,请务必至少阅读您正在使用的库的参考手册。

来源:
https://xlrd.readthedocs.io/en/latest/api.html
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html

这些网站上有大量信息和示例。