pandas の corr メソッドを使って、相関マトリックスを作成するサンプルコードを紹介します。
出力結果例
以下のような結果がスピルして表示されます。

corr メソッドの構文
DataFrame.corr([method, min_periods, numeric_only])
戻り値 | DataFrame |
引数 | 型 | 説明 |
---|---|---|
method (任意) | string or 関数 | 選択肢: ・”pearson”(ピアソンの積率相関係数) ・”kendall”(ケンドールの順位相関係数) ・”spearman”(スピアマンの順位相関係数) ・関数を指定 デフォルト:”pearson” |
min_periods (任意) | int | 列のペアごとに必要な観測値の最小数 ピアソン相関とスピアマン相関でのみ使用可 デフォルト:1 |
numeric_only (任意) | bool | float、int、bool データのみを含める デフォルト:True |
サンプルコード
Pythonの入力方法や出力種類、DataFrameの定義方法については、以下の記事で詳しく紹介しています。

【超基本】Python in Excel の使い方とルール
Python in Excel の入力方法は難しくはありませんが、Excelのワークシート関数の入力の仕方とは少し勝手が違います。この記事では、Python in Excel の入力の仕方と出力の種類、計算順序やパフォーマンスを向上させるた...

[DataFrame] xl関数の指定方法いろいろ
この記事では、DataFrameの定義、xl関数の使い方や注意点について説明します。DataFrameを使うと、Excelのセル範囲や名前、テーブル、Power Queryのデータを Python in Excel で扱えるようになります。...
引数なし
sample_df = xl("IrisDataSet2[#すべて]", headers=True)
sample_df.corr()
# 以下と同じ結果を得られる
# sample_df.corr(method="pearson", min_periods=1, numeric_only=True)
結果 相関マトリックスがスピルして表示されます。

引数 method を指定
sample_df = xl("IrisDataSet2[#すべて]", headers=True)
sample_df.corr(method="pearson")
結果 ピアソンの積率相関係数を用いた結果

sample_df = xl("IrisDataSet2[#すべて]", headers=True)
sample_df.corr(method="kendall")
結果 ケンドールの順位相関係数を用いた結果

sample_df = xl("IrisDataSet2[#すべて]", headers=True)
sample_df.corr(method="spearman")
結果 スピアマンの順位相関係数を用いた結果

引数 method に関数を指定
# 関数を定義(引数に1次元配列を2つ取り、戻り値がfloat)
def histogram_intersection(a, b):
v = np.minimum(a, b).sum().round(decimals=1)
return v
sample_df = xl("IrisDataSet2[#すべて]", headers=True)
sample_df.corr(method=histogram_intersection) # 関数(名)を渡す
結果

引数 numeric_only を指定
sample_df = xl("IrisDataSet2[#すべて]", headers=True)
sample_df.corr(numeric_only=False)
結果 この引数の用途がよく分からない…

注意点
numeric_only 引数のデフォルト値は、pandasのバージョン2.0.0から False に変わったようですが、2023年11月現在、Python in Excel で使用されるクラウド上の pandasのバージョンは「1.5.3」なので、numeric_only 引数のデフォルト値は True です。

クラウド上のライブラリのバージョンアップは今後どうなるのかよく分からないですが、バージョンアップされても問題なく動作するように作っておきたいというしっかり者の皆さんは、numeric_only 引数を明示的に指定しておきましょう。
sample_df.corr(numeric_only=True) # 任意引数だけど明示的に指定しておく