Python pandas correlation corr() TypeError: Could not compare ['pearson'] with block values
Python pandas correlation corr() TypeError: Could not compare ['pearson'] with block values
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)
我认为它应该 return a float = -1.00 但它却产生了以下错误:
TypeError: Could not compare ['pearson'] with block values
在此先感谢您的帮助。
pandas.DataFrame.corr
计算单个数据帧的列之间的成对相关性。这里需要的是 pandas.DataFrame.corrwith
:
>>> one.corrwith(two)
0 -1
dtype: float64
你在 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
中的列时,它将 return 为 Series
,这是一维的。此函数的文档是 here.
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)
我认为它应该 return a float = -1.00 但它却产生了以下错误:
TypeError: Could not compare ['pearson'] with block values
在此先感谢您的帮助。
pandas.DataFrame.corr
计算单个数据帧的列之间的成对相关性。这里需要的是 pandas.DataFrame.corrwith
:
>>> one.corrwith(two)
0 -1
dtype: float64
你在 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
中的列时,它将 return 为 Series
,这是一维的。此函数的文档是 here.