Python pandas correlation corr()TypeError:无法将['pearson']与块值进行比较

时间:2015-09-11 17:40:29

标签: python pandas typeerror correlation pearson

one = pd.DataFrame(data=[1,2,3,4,5], index=[1,2,3,4,5])

two = pd.DataFrame(data=[5,4,3,2,1], index=[1,2,3,4,5])

one.corr(two)

我认为它应该返回一个float = -1.00,但它会产生以下错误:

  

TypeError:无法将['pearson']与块值进行比较

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:7)

pandas.DataFrame.corr计算单个数据帧的列之间的成对相关性。你需要的是pandas.DataFrame.corrwith

>>> one.corrwith(two)
0   -1
dtype: float64

答案 1 :(得分:2)

当您应该使用DataFrame时,您正在使用Series

In [1]: import pandas as pd

In [2]: one = pd.DataFrame(data=[1,2,3,4,5], index=[1,2,3,4,5])

In [3]: two = pd.DataFrame(data=[5,4,3,2,1], index=[1,2,3,4,5])

In [4]: one
Out[4]:
   0
1  1
2  2
3  3
4  4
5  5

In [5]: two
Out[5]:
   0
1  5
2  4
3  3
4  2
5  1

In [6]: one[0].corr(two[0])
Out[6]: -1.0

为什么下标[0]?因为这是DataFrame中列的名称,因为您没有给它一个。当您引用DataFrame中的列时,它将返回Series,这是1维的。此功能的文档是here