7
8

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 5 years have passed since last update.

生データのpandas dfから偏相関行列を求めるプログラム

Last updated at Posted at 2019-09-25

要点

コード

p_corr.py
# df: tidy data, column are variable names, index is obs id.
# using numpy as np, pandas as pd
def df_partial_corr(df):
	temp_cov = df.cov()
	omega = np.linalg.inv(temp_cov)
	D = np.diag(np.power(np.diag(omega), -0.5))
	temp_pcorr = -np.dot(np.dot(D, omega), D) \
                         + 2*np.eye(temp_cov.shape[0])
	mtx_pcorr = pd.DataFrame(temp_pcorr, 
                             columns = temp_cov.columns,
                             index = temp_cov.index)
	return mtx_pcorr

検証

この記事のデータを用いて、この記事がRで偏相関行列を求めているので、これを再現。(元ネタ記事の検証を行列に拡張しただけですね)
df_pcorr = df_partial_corr(df) の中身をのぞいてみると、
Capture.PNG
問題なく再現できているようです。

参考文献

重回帰、偏相関、パス解析 by 大垣俊一,Argonauta 13: 3-23 (2007)

7
8
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
7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?