Python で平均・分散・標準偏差を計算する(NumPy)

NumPy を使うと、配列データの平均・分散・標準偏差を簡単に計算できます。手計算と比較しながら、基本的な使い方を確認しましょう。

NumPy のインポートとデータ準備

まず NumPy をインポートし、サンプルデータを用意します。

import numpy as np

# サンプルデータ(テストの点数)
scores = np.array([72, 85, 68, 91, 74, 80, 77, 88, 69, 76])

平均の計算

平均は np.mean() で計算します。

mean = np.mean(scores)
print(f"平均: {mean}")

実行結果は 平均: 78.0 となります。手計算では なので一致しています。

分散の計算

分散は np.var() で計算します。デフォルトでは母分散( で割る)が計算されます。

# 母分散(デフォルト)
var_population = np.var(scores)
print(f"母分散: {var_population}")

# 標本分散(n-1 で割る)
var_sample = np.var(scores, ddof=1)
print(f"標本分散: {var_sample}")

実行結果は 母分散: 52.0標本分散: 57.777... となります。ddof パラメータは自由度の調整値で、ddof=1 とすると標本分散が得られます。

標準偏差の計算

標準偏差は np.std() で計算します。分散と同様に ddof パラメータで調整できます。

# 母標準偏差
std_population = np.std(scores)
print(f"母標準偏差: {std_population:.4f}")

# 標本標準偏差
std_sample = np.std(scores, ddof=1)
print(f"標本標準偏差: {std_sample:.4f}")

実行結果は 母標準偏差: 7.2111標本標準偏差: 7.6012 となります。

まとめて計算する

複数の統計量をまとめて確認したい場合は、次のように書けます。

print(f"データ数: {len(scores)}")
print(f"合計: {np.sum(scores)}")
print(f"平均: {np.mean(scores)}")
print(f"分散: {np.var(scores, ddof=1):.4f}")
print(f"標準偏差: {np.std(scores, ddof=1):.4f}")
print(f"最小値: {np.min(scores)}")
print(f"最大値: {np.max(scores)}")

NumPy の関数は大規模なデータでも高速に動作するため、実務でのデータ分析に欠かせないツールです。