在Python中创建相关系数矩阵的六种方法

简介: 在Python中创建相关系数矩阵的六种方法

相关系数矩阵(Correlation matrix)是数据分析的基本工具。它们让我们了解不同的变量是如何相互关联的。在Python中,有很多个方法可以计算相关系数矩阵,今天我们来对这些方法进行一个总结

Pandas

Pandas的DataFrame对象可以使用corr方法直接创建相关矩阵。由于数据科学领域的大多数人都在使用Pandas来获取数据,因此这通常是检查数据相关性的最快、最简单的方法之一。

复制

import pandas as pd
 import seaborn as sns
 data = sns.load_dataset('mpg')
 correlation_matrix = data.corr(numeric_only=True)
 correlation_matrix• 1.
• 2.
• 3.
• 4.
• 5.
• 6.

如果你是统计和分析相关工作的,你可能会问" p值在哪里?",在最后我们会有介绍

Numpy

Numpy也包含了相关系数矩阵的计算函数,我们可以直接调用,但是因为返回的是ndarray,所以看起来没有pandas那么清晰。

复制

import numpy as np
 from sklearn.datasets import load_iris
 iris = load_iris()
 np.corrcoef(iris["data"])• 1.
• 2.
• 3.
• 4.
• 5.

为了更好的可视化,我们可以直接将其传递给sns.heatmap()函数。

复制

import seaborn as sns
 data = sns.load_dataset('mpg')
 correlation_matrix = data.corr()
 sns.heatmap(data.corr(), 
            annot=True, 
            cmap='coolwarm')• 1.
• 2.
• 3.
• 4.
• 5.
• 6.
• 7.
• 8.

annot=True这个参数可以输出一些额外的有用信息。一个常见hack是使用sns.set_context('talk')来获得额外的可读输出。

这个设置是为了生成幻灯片演示的图像,它能帮助我们更好地阅读(更大的字体)。

Statsmodels

Statsmodels这个统计分析库也是肯定可以的

复制

import statsmodels.api as sm
 correlation_matrix = sm.graphics.plot_corr(
    data.corr(), 
    xnames=data.columns.tolist())• 1.
• 2.
• 3.
• 4.
• 5.

plotly

默认情况下plotly这个结果是如何从左下到右上运行对角线1.0的。这种行为与大多数其他工具相反,所以如果你使用plotly需要特别注意

复制

import plotly.offline as pyo
 pyo.init_notebook_mode(cnotallow=True)
 import plotly.figure_factory as ff
 correlation_matrix = data.corr()
 fig = ff.create_annotated_heatmap(
    z=correlation_matrix.values, 
    x=list(correlation_matrix.columns), 
    y=list(correlation_matrix.index), 
    colorscale='Blues')
 fig.show()• 1.
• 2.
• 3.
• 4.
• 5.
• 6.
• 7.
• 8.
• 9.
• 10.
• 11.
• 12.
• 13.
• 14.

Pandas + Matplotlib更好的可视化

这个结果也可以直接使用用sns.pairplot(data),两种方法产生的图差不多,但是seaborn只需要一句话

复制

sns.pairplot(df[['mpg','weight','horsepower','acceleration']])• 1.

所以我们这里介绍如何使用Matplotlib来实现

复制

import matplotlib.pyplot as plt
 pd.plotting.scatter_matrix(
    data, alpha=0.2, 
    figsize=(6, 6), 
    diagnotallow='hist')
 plt.show()• 1.
• 2.
• 3.
• 4.
• 5.
• 6.
• 7.
• 8.

相关性的p值

如果你正在寻找一个简单的矩阵(带有p值),这是许多其他工具(SPSS, Stata, R, SAS等)默认做的,那如何在Python中获得呢?

这里就要借助科学计算的scipy库了,以下是实现的函数

复制

from scipy.stats import pearsonr
 import pandas as pd
 import seaborn as sns
 def corr_full(df, numeric_notallow=True, rows=['corr', 'p-value', 'obs']):
    """
    Generates a correlation matrix with correlation coefficients, 
    p-values, and observation count.
    Args:
    - df:                 Input dataframe
    - numeric_only (bool): Whether to consider only numeric columns for 
                            correlation. Default is True.
    - rows:               Determines the information to show. 
                            Default is ['corr', 'p-value', 'obs'].
    Returns:
    - formatted_table: The correlation matrix with the specified rows.
    """
    # Calculate Pearson correlation coefficients
    corr_matrix = df.corr(
        numeric_notallow=numeric_only)
    # Calculate the p-values using scipy's pearsonr
    pvalue_matrix = df.corr(
        numeric_notallow=numeric_only, 
        method=lambda x, y: pearsonr(x, y)[1])
    # Calculate the non-null observation count for each column
    obs_count = df.apply(lambda x: x.notnull().sum())
    # Calculate observation count for each pair of columns
    obs_matrix = pd.DataFrame(
        index=corr_matrix.columns, columns=corr_matrix.columns)
    for col1 in obs_count.index:
        for col2 in obs_count.index:
            obs_matrix.loc[col1, col2] = min(obs_count[col1], obs_count[col2])
    # Create a multi-index dataframe to store the formatted correlations
    formatted_table = pd.DataFrame(
        index=pd.MultiIndex.from_product([corr_matrix.columns, rows]), 
        columns=corr_matrix.columns
    )
    # Assign values to the appropriate cells in the formatted table
    for col1 in corr_matrix.columns:
        for col2 in corr_matrix.columns:
            if 'corr' in rows:
                formatted_table.loc[
                    (col1, 'corr'), col2] = corr_matrix.loc[col1, col2]
            if 'p-value' in rows:
                # Avoid p-values for diagonal they correlate perfectly
                if col1 != col2:
                    formatted_table.loc[
                        (col1, 'p-value'), col2] = f"({pvalue_matrix.loc[col1, col2]:.4f})"
            if 'obs' in rows:
                formatted_table.loc[
                    (col1, 'obs'), col2] = obs_matrix.loc[col1, col2]
    return(formatted_table.fillna('')
            .style.set_properties(**{'text-align': 'center'}))• 1.
• 2.
• 3.
• 4.
• 5.
• 6.
• 7.
• 8.
• 9.
• 10.
• 11.
• 12.
• 13.
• 14.
• 15.
• 16.
• 17.
• 18.
• 19.
• 20.
• 21.
• 22.
• 23.
• 24.
• 25.
• 26.
• 27.
• 28.
• 29.
• 30.
• 31.
• 32.
• 33.
• 34.
• 35.
• 36.
• 37.
• 38.
• 39.
• 40.
• 41.
• 42.
• 43.
• 44.
• 45.
• 46.
• 47.
• 48.
• 49.
• 50.
• 51.
• 52.
• 53.
• 54.
• 55.
• 56.
• 57.
• 58.
• 59.
• 60.
• 61.
• 62.
• 63.

直接调用这个函数,我们返回的结果如下:

复制

df = sns.load_dataset('mpg')
 result = corr_full(df, rows=['corr', 'p-value'])
 result• 1.
• 2.
• 3.

总结

我们介绍了Python创建相关系数矩阵的各种方法,这些方法可以随意选择(那个方便用哪个)。Python中大多数工具的标准默认输出将不包括p值或观察计数,所以如果你需要这方面的统计,可以使用我们子厚提供的函数,因为要进行全面和完整的相关性分析,有p值和观察计数作为参考是非常有帮助的。

相关文章
|
4天前
|
Python
Python面向对象基础与魔法方法详解
Python面向对象基础与魔法方法详解
|
8天前
|
Python
python中使用update()方法
【6月更文挑战第16天】
17 7
|
4天前
|
监控 安全 虚拟化
深入浅出Python沙箱越狱:原理、方法与防范
今天我们来聊一个有趣的话题 - Python沙箱越狱。在我们开始之前,先来搞清楚什么是Python沙箱吧。 简单来,Python沙箱就像是一个虚拟的"游乐场"。在这个游乐场里,你可以尽情地玩耍(运行Python代码),但是不能伤害到外面的世界(不能访问系统资源或执行危险操作)。这个"游乐场"有围栏(限制),有规则(安全策略),目的就是让你玩得开心,又不会搞出什么大乱子。
|
6天前
|
机器学习/深度学习 数据处理 索引
Python遍历矩阵的技巧与实践
Python遍历矩阵的技巧与实践
16 2
|
5天前
|
Python
python之字符串定义、切片、连接、重复、遍历、字符串方法
python之字符串定义、切片、连接、重复、遍历、字符串方法
6 0
python之字符串定义、切片、连接、重复、遍历、字符串方法
|
6天前
|
计算机视觉 Python
Python矩阵转灰度图技术解析
Python矩阵转灰度图技术解析
5 1
|
11天前
|
Python
Python三种标准输出重定向方法
Python 提供了标准库中的 sys.stdout 对象来代表标准输出。如果我们想将输出重定向到其他位置,例如内存、文件或自定义类,我们可以通过一些技巧来实现。
16 2
|
11天前
|
存储 缓存 调度
Python教程:一文了解10种数据结构在Python中的实现方法
数据结构是计算机科学中非常重要的概念,它用于组织和存储数据,使得数据可以高效地被访问和操作。在编程中,选择合适的数据结构对于解决问题和提高程序性能至关重要。
22 1
|
2天前
|
机器学习/深度学习 TensorFlow 算法框架/工具
使用Python实现深度学习模型:策略梯度方法
使用Python实现深度学习模型:策略梯度方法
4 0
|
3天前
|
关系型数据库 MySQL 数据库
Python中使用MySQL模糊查询的方法
(1)同样需要将your_username、your_password、your_database替换为我们的MySQL数据库的实际用户名、密码和数据库名。 (2)在mysql.connector.connect()中,我们没有直接指定字符集和游标类型,因为mysql-connector-python的默认配置通常已经足够好。但是,如果需要,我们可以添加这些配置选项。 (3)使用cursor.close()和cnx.close()来确保游标和连接都被正确关闭。 (4)mysql-connector-python也支持使用上下文管理器(即with语句)来自动管理游标和连接的关闭,但这需要创建一个