You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法绘制散点图:pandas scatter_matrix调用报错求助

解决方案:修复pandas scatter_matrix绘制散点矩阵的错误

问题根源分析

  1. 第一次代码报错'Series' object has no attribute 'columns':
    pd.concat([df_NVDA['Returns'], df_AVGO['Returns']])默认按**行(axis=0)**拼接两个Series,最终得到的是一个长Series而非DataFrame,因此无法设置columns属性。

  2. 第二次修改后仍有问题的潜在原因:

    • 单独对每个Returns列执行dropna(),导致三个DataFrame的行数/索引不一致,拼接后出现大量缺失值,干扰散点矩阵绘制。
    • 提前调用plt.figure(),而scatter_matrix内部会自动创建绘图容器,重复创建可能导致渲染异常。
    • 未确保所有必要库(如matplotlib.pyplot)已导入。

修正后的完整代码

import pandas as pd
from pandas.plotting import scatter_matrix
import matplotlib.pyplot as plt

# 计算每日收益率(保留原索引,暂不单独删除缺失值)
df_NVDA['Returns'] = df_NVDA['Open'].pct_change(1)
df_AVGO['Returns'] = df_AVGO['Open'].pct_change(1)
df_PFE['Returns'] = df_PFE['Open'].pct_change(1)

# 按列拼接为DataFrame,统一删除含缺失值的行(保证三列数据行对齐)
NVDA_AVGO_PFE = pd.concat(
    [df_NVDA['Returns'], df_AVGO['Returns'], df_PFE['Returns']],
    axis=1
).dropna()

# 重命名列名
NVDA_AVGO_PFE.columns = ['NVIDIA', 'Broadcom', 'Pfizer']

# 绘制散点矩阵(无需提前创建plt.figure)
scatter_matrix(
    NVDA_AVGO_PFE,
    figsize=(12, 10),
    alpha=1.0,
    hist_kwds={'bins': 40}
)

# Jupyter Notebook中可省略plt.show(),但添加后兼容性更好
plt.show()

关键修正点说明

  • 拼接方式:必须指定axis=1按列拼接,确保得到多列的DataFrame,而非单行Series。
  • 缺失值处理:拼接后统一执行dropna(),避免因单个Series行数不一致导致的对齐问题。
  • 绘图容器:scatter_matrix会自动创建figure和axes,无需提前调用plt.figure(),否则可能导致图层冲突。
  • 参数正确性:确保hist_kwds中使用bins而非拼写错误的bin(你第二次修改已修正此点)。

内容的提问来源于stack exchange,提问作者Minh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 10:12:38