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

调用sns.histplot时出现ValueError: output array is read-only错误求助

解决sns.histplot触发"ValueError: output array is read-only"错误

这个错误的核心原因是你使用的DataFrame(df)里的数值列存储在只读数组中——seaborn绘制KDE曲线时需要对数据做临时计算,而只读数组不允许修改操作,直接触发报错。

下面是几种可行的解决办法:

  • 复制整个DataFrame为可写副本
    在绘图代码前加一行df = df.copy(),生成一个完全可修改的DataFrame副本,后续绘图就不会受只读限制了。修改后的完整代码:

    # Numerical columns to visualize
    numerical_columns = ['age', 'avg_glucose_level', 'bmi']
    # 生成可写的DataFrame副本
    df = df.copy()
    fig, axes = plt.subplots(nrows=len(numerical_columns), ncols=1, figsize=(10, 5 * len(numerical_columns)))
    # Plot histograms for each numerical column
    for col, ax in zip(numerical_columns, axes):
        sns.histplot(x=col, hue='stroke', data=df, kde=True, ax=ax, bins=30)
        ax.set_title(f'Histogram of {col} vs Stroke')
        ax.set_xlabel(col)
        ax.set_ylabel('Count')
    
    plt.tight_layout()
    plt.show()
    
  • 单独转换需要的数值列
    如果不想复制整个DataFrame,只针对要绘图的列做转换,把它们转为可写数组:

    # 在绘图循环前执行
    for col in numerical_columns:
        df[col] = df[col].to_numpy().copy()
    
  • 检查数据源的加载模式
    如果你的DataFrame是从外部文件加载的(比如HDF5、CSV等),确认加载时没有设置只读模式。比如用pd.read_hdf()时如果加了mode='r',后续一定要转为可写副本再操作。

内容的提问来源于stack exchange,提问作者Shahed Iqbal Chowdhury

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 01:22:41