<p>没有理由使用pandas从excel文件中读取数据,然后将其转换为列表并重新执行基本向量操作,如均值和方差</p>
<pre class="lang-py prettyprint-override"><code>from os import path
import pandas as pd
class Taraz:
def __init__(self, filepath):
scores = pd.read_excel(filepath)['point']
self.mean = scores.mean()
self.var = scores.var()
def score(self, score):
return (score - self.mean) / self.var
if __name__ == '__main__':
taraz = Taraz(path.join('path', 'to', 'the', 'file.xlsx'))
print(taraz.score(16))
</code></pre>
<p>输出:</p>
<pre><code>-0.012571428571428395
</code></pre>
<p>在你的例子中,你有几个错误,我想评论一下</p>
<ol>
<li>变量范围很重要。如果在函数中指定变量,则该变量将仅在该函数中指定。超出此范围将引发名称错误</李>
<li>方法第一个参数(除了一些特殊的方法外,它应该被称为<code>self</code>)是实例本身,我们可以在其中分配将存储在实例中的值,然后检索它们。例如,在上面代码的构造函数(<code>__init__</code>)方法中,我们将一些内容分配给<code>self.mean</code>,该值将存储在实例中,以便稍后在out<code>score</code>方法中使用它</李>
<li>OOP(面向对象编程)是一种非常成熟的编码模式,但试图强制使用类来表示并不真正表示类型的内容似乎有点不必要。这可以通过单个功能轻松实现:</li>
</ol>
<pre class="lang-py prettyprint-override"><code>from os import path
import pandas as pd
def taraz(filepath):
scores = pd.read_excel(filepath)
mean = scores['point'].mean()
var = scores['point'].var()
scores['scores'] = (scores['point'] - mean) / var
return scores
if __name__ == '__main__':
print(taraz(path.join('path', 'to', 'the', 'file.xlsx')))
</code></pre>
<p>输出:</p>
<pre><code> name point scores
0 tghi 15 -0.163429
1 nghi 16 -0.012571
2 asghr 15 -0.163429
3 sbhn 20 0.590857
4 tghi 12 -0.616000
5 nghi 20 0.590857
6 asghr 17 0.138286
7 sbhn 18 0.289143
8 tghi 17 0.138286
9 nghi 16 -0.012571
10 asghr 15 -0.163429
11 12 -0.616000
</code></pre>
<p>如您所见,熊猫数据帧实现向量运算,因此<code>(scores['point'] - mean) / var</code>被转换为整数向量减去一个浮点数,再除以一个浮点数,该运算的结果是一个浮点数向量,我们将其存储在“scores”列中。这样我们计算每一行的分数</p>