Python Corr() - ValueError: 无法将字符串转换为浮点数

8
我在尝试按照Python中使用corr()方法的练习时遇到了一个非常奇怪的错误。

https://www.geeksforgeeks.org/python-pandas-dataframe-corr/

具体来说,当我尝试运行以下代码时:df.corr(method ='pearson') 错误信息没有给出任何线索。我原以为corr()方法应该自动忽略字符串和空值等。
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    df.corr(method='pearson')
  File "C:\Users\d.o\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\frame.py", line 10059, in corr
    mat = data.to_numpy(dtype=float, na_value=np.nan, copy=False)
  File "C:\Users\d.o\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\frame.py", line 1838, in to_numpy
    result = self._mgr.as_array(dtype=dtype, copy=copy, na_value=na_value)
  File "C:\Users\d.o\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\internals\managers.py", line 1732, in as_array
    arr = self._interleave(dtype=dtype, na_value=na_value)
  File "C:\Users\d.o\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\internals\managers.py", line 1794, in _interleave
    result[rl.indexer] = arr
ValueError: could not convert string to float: 'Avery Bradley'

谢谢


那个错误信息中的最后一行告诉你,你的程序以某种方式包含了术语"Avery Bradley"...而奇怪的是,Avery Bradley似乎与任何数据都没有相关性!(哈哈哈)。无论如何,如果你仍然需要帮助,你需要展示你用于此操作的代码来进行故障排除。 - undefined
谢谢 @AirSquid。代码就是这样的。import pandas as pd, df = pd.read_csv("nba.csv") 和 df.corr(method ='pearson'),就像教程中所示。你能否复制出现的错误?据我所了解,corr()方法应该忽略字符串和空白。 - undefined
3个回答

19
自从pandas版本2.0.0以后,现在你需要添加numeric_only=True参数来避免这个问题。

2
当我尝试复制这个行为时,corr()方法可以正常工作,但会输出一个警告(如下所示),警告说将来将删除对非数字列的忽略。也许未来已经到来了?
我使用的是pandas版本1.5.3。
你可能需要指定要使用的列,这实际上是一种更好的做法,而不是依赖于pd来为你完成。你可以通过提供感兴趣的列的列表作为索引来实现这一点(如下所示)。
In [1]: import pandas as pd

In [2]: data = {'name': ['bob', 'cindy', 'tom'],
   ...:         'x'   : [ 1,     2,      3   ],
   ...:         'y'   : [ 6.5,   8.9,    12.0]}

In [3]: df = pd.DataFrame(data)

In [4]: df
Out[4]: 
    name  x     y
0    bob  1   6.5
1  cindy  2   8.9
2    tom  3  12.0

In [5]: df.describe()
Out[5]: 
         x          y
count  3.0   3.000000
mean   2.0   9.133333
std    1.0   2.757414
min    1.0   6.500000
25%    1.5   7.700000
50%    2.0   8.900000
75%    2.5  10.450000
max    3.0  12.000000

In [6]: df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   name    3 non-null      object 
 1   x       3 non-null      int64  
 2   y       3 non-null      float64
dtypes: float64(1), int64(1), object(1)
memory usage: 200.0+ bytes

In [7]: df.corr(method='pearson')
<ipython-input-7-432dd9d4238b>:1: FutureWarning: The default value of numeric_only in DataFrame.corr is deprecated. In a future version, it will default to False. Select only valid columns or specify the value of numeric_only to silence this warning.
  df.corr(method='pearson')
Out[7]: 
          x         y
x  1.000000  0.997311
y  0.997311  1.000000

In [8]: df[['x', 'y']].corr(method='pearson')
Out[8]: 
          x         y
x  1.000000  0.997311
y  0.997311  1.000000

谢谢!现在可以工作了。他们一定停止了那个强制人们指定列的旧功能。 - undefined
1
看起来是这样的。此外,在将来,一个好的首要地方是查找特定函数的文档,您正在尝试使用该函数。Pandas 2.0中有关此函数的文档提到了这一点:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.corr.html - undefined

0

我也遇到了同样的问题,现在我使用

df.corr(numeric_only=True)

它解决了我的问题。你也可以试试看。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接