pandas.DataFrame.corr#

DataFrame.corr(method='pearson', min_periods=1, numeric_only=False)[source]#

计算列的成对相关性,排除 NA/null 值。

参数:
method{‘pearson’, ‘kendall’, ‘spearman’} 或可调用对象

相关性方法

  • pearson : 标准相关系数

  • kendall : Kendall Tau 相关系数

  • spearman : Spearman 秩相关

  • callable: 接收两个一维 ndarray 并返回一个浮点数的函数

    并返回一个浮点数。请注意,corr 返回的矩阵的对角线将为 1,并且无论可调用对象的行为如何,它都将是对称的。

min_periodsint, optional

每对列需要的最少观测值,才能获得有效结果。目前仅适用于 Pearson 和 Spearman 相关性。

numeric_onlybool, default False

仅包含 floatintboolean 数据。

版本 2.0.0 已更改: numeric_only 的默认值现在是 False

返回:
DataFrame

相关性矩阵。

另请参阅

DataFrame.corrwith

计算与其他 DataFrame 或 Series 的成对相关性。

Series.corr

计算两个 Series 之间的相关性。

注意

Pearson、Kendall 和 Spearman 相关性目前是使用成对完整观测值计算的。

示例

>>> def histogram_intersection(a, b):
...     v = np.minimum(a, b).sum().round(decimals=1)
...     return v
>>> df = pd.DataFrame(
...     [(0.2, 0.3), (0.0, 0.6), (0.6, 0.0), (0.2, 0.1)],
...     columns=["dogs", "cats"],
... )
>>> df.corr(method=histogram_intersection)
      dogs  cats
dogs   1.0   0.3
cats   0.3   1.0
>>> df = pd.DataFrame(
...     [(1, 1), (2, np.nan), (np.nan, 3), (4, 4)], columns=["dogs", "cats"]
... )
>>> df.corr(min_periods=3)
      dogs  cats
dogs   1.0   NaN
cats   NaN   1.0