0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Python] 相関係数を計算したい

Last updated at Posted at 2021-11-15

はじめに

Pythonを使ってデータの相関係数を計算する方法を何通りか示します。

使用データ

方法を示すだけなので適当なデータ

data.csv
sqrt2,pi
1,3
4,1
1,4
4,1
2,5
1,9
3,2
5,6
6,5

を使用します。

計算方法例

Pandas

一番簡単なやりかたですね

import pandas as pd
df = pd.read_csv('./data.csv')
print(df.corr())

          sqrt2        pi
sqrt2  1.000000 -0.205738
pi    -0.205738  1.000000

NumPy

import numpy as np
import pandas as pd

df = pd.read_csv('./data.csv')
col1 = df['sqrt2'].tolist()
col2 = df['pi'].tolist()

print(np.corrcoef(col1, col2))

[[ 1.        -0.2057378]
 [-0.2057378  1.       ]]

NumPyその2

データの読み込みにpandasを使っているのでわざわざNumPyにする必要がない…という方のために

import csv
import numpy as np

with open('./data.csv') as f:
	reader = csv.DictReader(f)
	col1, col2 = [], []
	for row in reader:
		col1.append(float(row['sqrt2']))
		col2.append(float(row['pi']))

print(np.corrcoef(col1, col2))

[[ 1.        -0.2057378]
 [-0.2057378  1.       ]]

(Pandasでいいじゃん…)

自前で頑張る

ライブラリなんて使いたくない人向けです
(だったら正直Pythonである必要がないと思いますが)

with open('./data.csv') as f:
	lines = f.readlines()[1:]

col1, col2 = [], []
for line in lines:
	data = list(map(float, line.split(',')))
	col1.append(data[0])
	col2.append(data[1])

def avg(l):
	return sum(l) /len(l)

def s(l1, l2):
	avg1, avg2 = avg(l1), avg(l2)
	return sum((v1-avg1)*(v2-avg2) for v1, v2 in zip(l1, l2))

r = s(col1, col2) / (s(col1, col1) * s(col2, col2)) ** .5
print(r)

-0.20573779994945587

さいごに

下に行くほどPythonである必要性を失っている気がしますが自分が何をしているのかが見えやすいという意味では勉強になるのではないでしょうか

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?