Pythonでデータ処理入門 テストデータをまとめよう!



今回はPythonでデータ処理の入門や活用の仕方の例として、テストのデータをまとめて平均点や偏差値を自動で求めてくれるプログラムをつくりましょう!

作るのは、このようなものです。

a,95
b,50
c,30
d,15
e,70
f,60
g,65
h,20
i,95

名前,テストの点数 のデータを


このように処理して偏差値などのデータにまとめてくれるプログラムです。

では作っていきましょう!


まずは平均点を求める関数を作りましょう。
def calculate_average(scores):
    return sum(scores) / len(scores)
scoresというのは、全員の点数のデータの入ったリストです。例えば[10,50,90]

sum関数は、引数の合計を返す関数です。
len関数は、引数のデータの個数を返す関数です。
つまり、データの合計/データの個数 なので平均を求められます。returnで値を返します。

次に、標準偏差を求める関数を作ります。
偏差値を求めるには標準偏差は不可欠です。
def calculate_std_deviation(scores, mean):
    variance = sum((x - mean) ** 2 for x in scores) / len(scores)
    return variance ** 0.5

meanは、平均点のことです。
varianceは、個々の点数と平均点の差の2乗の合計を、データの個数で割ったものです。
それの平方根を返します。
これで標準偏差が求められます。

では偏差値を求める関数を作りましょう。
def calculate_z_score(score, mean, std_deviation):
    return 50 + 10 * ((score - mean) / std_deviation)
std_deviationが標準偏差です。
scoreは個々の点数のことなので、これで偏差値が返されます。
for文を使ってそれぞれのデータを代入しないのは、この関数を呼び出すときに同じようなことをするからです。詳しくは後ほど出てきます。

パーセンタイル順位を求める関数です。
def calculate_percentile_rank(score, sorted_scores):
    count_below = sum(1 for x in sorted_scores if x < score)
    return (count_below / (len(sorted_scores)-1)) * 100
sorted_scoresは、点数データを昇順に並び替えたものです。
もちろんパーセンタイル順位を返します。

次は、テキストファイルからデータを読み取る関数を作ります。
def read_scores_from_file(filename):
    scores = []
    with open(filename, 'r') as file:
        for line in file:
            name, score_str = line.strip().split(',')
            score = float(score_str)
            scores.append((name, score))
    return scores
filename読み取るテキストファイルの名前です(パス含む)。
テキストファイルの中身は上であるように 名前,点数 を人数分入力したものにしてください。
今回は例として
a,95
b,50
c,30
d,15
e,70
f,60
g,65
h,20
i,95
というデータを使います。

話を戻して、関数の説明をすると、
まずはファイルを読み取りモード('r')で開きます。
for文では、各行順に読みあげ、','を境にnameとscore_str分割します。
得点の文字列を浮動小数点数に変換します。これにより、得点を数値として処理できるようになります
そして、名前と得点の組み合わせをタプルとしてリストscoresに追加します。
あとはscoresを戻り値として返して終了。

ではmain関数にいきます。
def main():
    filename = input("テキストファイル名を入力してください: ")
    student_scores = read_scores_from_file(filename)

    # テストの点数を抽出して、平均値と標準偏差を計算
    scores = [score for _, score in student_scores]
    average_score = calculate_average(scores)
    std_deviation = calculate_std_deviation(scores, average_score)
    sorted_scores = sorted(scores)

    print("\n--- 全体の統計情報 ---")
    print(f"平均点: {average_score:.2f}")
    print(f"標準偏差: {std_deviation:.2f}")

    for name, score in student_scores:
        z_score = calculate_z_score(score, average_score, std_deviation)
        percentile_rank = calculate_percentile_rank(score, sorted_scores)
        print("\n---", name, "---")
        print(f"点数: {score:.2f}")
        print(f"偏差値: {z_score:.2f}")
        print(f"パーセンタイルランク: {percentile_rank:.2f}%")

テキストファイルはコードを実行したときに指定できるようにinput関数で入力するようにしました。別に要らない人はそのままパスを書いてください。
ちなみにinput関数についてはこちらの記事で簡単に説明してます。
student_scoresには先ほどのread_scores_from_file関数scoresが返されます。
scoresには、点数データだけが入ります。
average_score平均点std_deviation標準偏差sorted_scores昇順にしたものです。
そして平均点と標準偏差を出力。
その下のfor文では、student_scoresから名前と点数をそれぞれnamescoreに代入し、
z_score偏差値percentile_rankパーセンタイル順位を代入して名前、点数とともに出力。これを人数分繰り返してます。

あとは、
if __name__ == "__main__":
    main()
実行されたらmain関数を呼ぶようにして、完成!

では実行しましょう。

テキストファイル名(パス)を入力すると、


ちゃんと出力されましたか?

たぶんいろいろ応用できるので、ぜひ活用してみてください!
また、出力結果もテキストファイルに書くようにしてみてもいいかもしれません。


最後に全体のコードを載せて終わります。

def calculate_z_score(score, mean, std_deviation):
    return 50 + 10 * ((score - mean) / std_deviation)

def calculate_average(scores):
    return sum(scores) / len(scores)

def calculate_std_deviation(scores, mean):
    variance = sum((x - mean) ** 2 for x in scores) / len(scores)
    return variance ** 0.5

def calculate_percentile_rank(score, sorted_scores):
    count_below = sum(1 for x in sorted_scores if x < score)
    return (count_below / (len(sorted_scores)-1)) * 100

def read_scores_from_file(filename):
    scores = []
    with open(filename, 'r') as file:
        for line in file:
            name, score_str = line.strip().split(',')
            score = float(score_str)
            scores.append((name, score))
    return scores

def main():
    filename = input("テキストファイル名を入力してください: ")
    student_scores = read_scores_from_file(filename)

    # テストの点数を抽出して、平均値と標準偏差を計算
    scores = [score for _, score in student_scores]
    average_score = calculate_average(scores)
    std_deviation = calculate_std_deviation(scores, average_score)
    sorted_scores = sorted(scores)

    print("\n--- 全体の統計情報 ---")
    print(f"平均点: {average_score:.2f}")
    print(f"標準偏差: {std_deviation:.2f}")

    for name, score in student_scores:
        z_score = calculate_z_score(score, average_score, std_deviation)
        percentile_rank = calculate_percentile_rank(score, sorted_scores)
        print("\n---", name, "---")
        print(f"点数: {score:.2f}")
        print(f"偏差値: {z_score:.2f}")
        print(f"パーセンタイルランク: {percentile_rank:.2f}%")

if __name__ == "__main__":
    main()

以上、Pythonでデータ処理入門 テストデータをまとめよう!でした。

このブログの人気の投稿

pythonで疑似ガチャGUIアプリを作ろう!(簡単)