pandas.DataFrame.corr#

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

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

Parameters:
<strong>method</strong>{‘pearson’, ‘kendall’, ‘spearman’} 或 callable

相关性方法:

  • pearson : 标准相关系数

  • kendall : Kendall Tau 相关系数

  • spearman : Spearman 秩相关系数

  • callable: callable,接收两个一维 ndarray 作为输入

    并返回一个 float。注意,corr 返回的矩阵在对角线上为 1,并且对称,无论 callable 的行为如何。

min_periodsint, optional

每对列需要的最少观测次数,才能得到有效结果。目前仅对 Pearson 和 Spearman 相关性可用。

numeric_onlybool,默认 False

仅包含 float, intboolean 数据。

在 1.5.0 版本加入.

在 2.0.0 版本发生变更: numeric_only 的默认值现在是 False

Returns:
DataFrame

相关矩阵。

参见

DataFrame.corrwith

计算与另一个 DataFrame 或 Series 的成对相关性。

Series.corr

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

Notes

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

Examples

>>> def histogram_intersection(a, b):
...     v = np.minimum(a, b).sum().round(decimals=1)
...     return v
>>> df = pd.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .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