1
0

Numpy 使うなら,ちゃんと使おう

Last updated at Posted at 2024-02-21

どうも,人工無脳はやたら長い変数名と,一時変数と,無駄なプログラミングを推してくるみたいですけど。

それに,結果をリストにして返すなんてもってのほか。

numpy を使うなら,ちゃんとベクトル計算をしましょう。

まさか,一文字当たりいくらという請負仕事なんでしょうか。

import numpy as np

def calculate_deviation_scores(scores):
    average_score = np.average(scores)  # 平均値を計算
    standard_deviation = np.std(scores)  # 標準偏差を計算
    deviation_scores = []  # 偏差値を格納するためのリスト

    # 各学生の偏差値を計算
    for score in scores:
        deviation_score = 50 + 10 * (score - average_score) / standard_deviation
        deviation_scores.append(deviation_score)

    return deviation_scores

# 模擬データ
scores = [92, 87, 78, 85, 90, 88, 77, 81, 80, 76]
# 各学生の偏差値を計算
deviation_scores = calculate_deviation_scores(scores)
print(deviation_scores)

[65.79644470496886, 56.6124652253358, 40.081302161996284, 52.93887343348257, 62.122852913115636, 58.44926112126241, 38.24450626606967, 45.59168984977612, 43.7548939538495, 36.40771037014306]

一行で書けるので,関数にするのも憚られます。

def calculate_deviation_scores(scores):
    return (scores - np.mean(scores))/np.std(scores) * 10 + 50

# 模擬データ
scores = [92, 87, 78, 85, 90, 88, 77, 81, 80, 76]
# 各学生の偏差値を計算
deviation_scores = calculate_deviation_scores(scores)
print(deviation_scores)

[65.7964447  56.61246523 40.08130216 52.93887343 62.12285291 58.44926112
 38.24450627 45.59168985 43.75489395 36.40771037]

更には scipy.stats には,z 得点を計算する zscore() があります。これを使うともっと簡単にかけます。

from scipy.stats import zscore
zscore(scores)*10+50
array([65.7964447 , 56.61246523, 40.08130216, 52.93887343, 62.12285291,
       58.44926112, 38.24450627, 45.59168985, 43.75489395, 36.40771037])
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0