Jupyter Notebook中ValueError报错排查求助
问题排查:Jupyter Notebook中Seaborn热力图报错ValueError
我在Anaconda的Jupyter Notebook中运行以下代码,教授的设备可正常执行,但我的设备在第三步出现ValueError。
运行步骤
步骤1
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd data = sns.load_dataset('diamonds')
步骤2
# Display the first five rows data.head()
步骤3
# Use a condensed heatmap to identify correlations for the price column. # Sort the results, include annotations that format the values with three decimal places, and remove the color bar. sns.heatmap(data=data.corr().sort_values(by="price", ascending=False), annot=True, fmt=".3f", cmap="coolwarm", cbar=False)
报错信息
ValueError Traceback (most recent call last) Cell In[3], line 3 1 #Use a condensed heatmap to identify correlations for the price column. 2 #Sort the results, include annotations that format the values with three decimal places, and remove the color bar. ----> 3 sns.heatmap(data=data.corr().sort_values(by="price", ascending=False), annot=True, fmt=".3f", cmap="coolwarm", cbar=False) File ~/anaconda3/lib/python3.11/site-packages/pandas/core/frame.py:10054, in DataFrame.corr(self, method, min_periods, numeric_only) 10052 cols = data.columns 10053 idx = cols.copy() > 10054 mat = data.to_numpy(dtype=float, na_value=np.nan, copy=False) 10056 if method == "pearson": 10057 correl = libalgos.nancorr(mat, minp=min_periods) File ~/anaconda3/lib/python3.11/site-packages/pandas/core/frame.py:1838, in DataFrame.to_numpy(self, dtype, copy, na_value) 1836 if dtype is not None: 1837 dtype = np.dtype(dtype) -> 1838 result = self._mgr.as_array(dtype=dtype, copy=copy, na_value=na_value) 1839 if result.dtype is not dtype: 1840 result = np.array(result, dtype=dtype, copy=False) File ~/anaconda3/lib/python3.11/site-packages/pandas/core/internals/managers.py:1732, in BlockManager.as_array(self, dtype, copy, na_value) 1730 arr.flags.writeable = False 1731 else: -> 1732 arr = self._interleave(dtype=dtype, na_value=na_value) ... 1346 # we need to ensure __array__ gets all the way to an 1347 # ndarray. 1348 return np.asarray(ret) ValueError: could not convert string to float: 'Ideal'
排查与解决建议
- 核心原因:新版pandas(2.0+)中
data.corr()默认不再自动排除字符串/类别型列,而diamonds数据集包含cut、color这类非数值列,导致计算相关性时无法将字符串转为浮点数报错。教授的设备可能使用的是pandas 1.x版本,该版本会自动忽略非数值列。 - 直接修复代码:在
corr()中添加numeric_only=True参数,明确只计算数值列的相关性:
sns.heatmap(data=data.corr(numeric_only=True).sort_values(by="price", ascending=False), annot=True, fmt=".3f", cmap="coolwarm", cbar=False)
- 版本验证:运行
print(pd.__version__)确认当前pandas版本,若为2.0+则需使用上述参数;若想保持原有逻辑,可降级至pandas 1.x版本:
pip install pandas==1.5.3
- 额外检查:执行
data.info()查看数据集列类型,确认非数值列的类型是否为object或category,确保数据加载正常。
内容的提问来源于stack exchange,提问作者Ari Zyskind
相关产品推荐
相关产品推荐

