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

两段相似代码执行报错‘setting an array element with a sequence’求助

问题排查:"setting an array element with a sequence"错误原因与解决方法

两段逻辑结构相似的代码,均通过列表构建数据集合后转为DataFrame,再调用seaborn的lmplot绘图。第一段代码触发ValueError: setting an array element with a sequence错误,第二段可正常运行。

报错代码

east_fg_data = [["Heat", miaFG, miaWin], ["Knicks", nykFG, nykWin], 
                ["Celitcs", bosFG, bosWin], ["76ers", phiFG, phiWin]]
east_fg_df = pd.DataFrame(east_fg_data, columns=['Teams', 'Field Goal Percentage', 'Wins'])

sns.lmplot(data = east_fg_df, x = 'Field Goal Percentage', y = 'Wins', hue = 'Teams',
          fit_reg = True, ci = 95)

正常运行代码

west_ex_data = [["Nuggets", denNet, denPoints], ["Grizzlies", memNet, memPoints], ["Kings", sacNet, sacPoints], 
                ["Suns", phxNet, phxPoints], ["Clippers", lacNet, lacPoints], ["Warriors", gswNet, gswPoints], 
                ["Lakers", lalNet, lalPoints], ["Timberwolves", minNet, minPoints], ["Pelicans", nopNet, nopPoints],
               ["Thunder", okcNet, okcPoints]]
west_ex_df = pd.DataFrame(west_ex_data, columns=['Teams', 'Net Field Goal Percentage', 'Wins'])

sns.lmplot(data = west_ex_df, x = 'Net Field Goal Percentage', y = 'Wins', hue = 'Teams')

报错信息

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/opt/anaconda3/lib/python3.9/site-packages/pandas/core/series.py in wrapper(self)
    184             return converter(self.iloc[0])
--> 185         raise TypeError(f"cannot convert the series to {converter}")
    186 

TypeError: cannot convert the series to <class 'float'>

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
/var/folders/n1/1bvy_hkj6d3chx2tpgxm3kt80000gn/T/ipykernel_50042/1816899590.py in <module>
      7 east_df = pd.DataFrame(east_data, columns=['Teams', 'Net Field Goal Percentage', 'Wins'])
      8 
----> 9 sns.lmplot(data = east_df, x = 'Net Field Goal Percentage', y = 'Wins', hue = 'Teams')

/opt/anaconda3/lib/python3.9/site-packages/seaborn/_decorators.py in inner_f(*args, **kwargs)
     44             )
     45         kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
--> 46         return f(**kwargs)
     47     return inner_f
     48 

/opt/anaconda3/lib/python3.9/site-packages/seaborn/regression.py in lmplot(x, y, data, hue, col, row, palette, col_wrap, height, aspect, markers, sharex, sharey, hue_order, col_order, row_order, legend, legend_out, x_estimator, x_bins, x_ci, scatter, fit_reg, ci, n_boot, units, seed, order, logistic, lowess, robust, logx, x_partial, y_partial, truncate, x_jitter, y_jitter, scatter_kws, line_kws, facet_kws, size)
    632         ax.autoscale_view(scaley=False)
    633 
--> 634     facets.map_dataframe(update_datalim, x=x, y=y)
    635 
    636     # Draw the regression plot on each facet

/opt/anaconda3/lib/python3.9/site-packages/seaborn/axisgrid.py in map_dataframe(self, func, *args, **kwargs)
    775 
    776             # Draw the plot
--> 777             self._facet_plot(func, ax, args, kwargs)
    778 
    779         # For axis labels, prefer to use positional args for backcompat

/opt/anaconda3/lib/python3.9/site-packages/seaborn/axisgrid.py in _facet_plot(self, func, ax, plot_args, plot_kwargs)
    804             plot_args = []
    805             plot_kwargs["ax"] = ax
--> 806         func(*plot_args, **plot_kwargs)
    807 
    808         # Sort out the supporting information

/opt/anaconda3/lib/python3.9/site-packages/seaborn/regression.py in update_datalim(data, x, y, ax, **kws)
    628 
    629     def update_datalim(data, x, y, ax, **kws):
--> 630         xys = np.asarray(data[[x, y]]).astype(float)
    631         ax.update_datalim(xys, updatey=False)
    632         ax.autoscale_view(scaley=False)

ValueError: setting an array element with a sequence.

报错原因

核心问题是报错代码中用于构建DataFrame的变量(如miaFG、miaWin等)不是单个数值,而是序列/数组类型。当你将序列类型的值放入列表再转为DataFrame时,对应的列会变成包含序列的对象列,而非数值列。而seaborn的lmplot要求x、y参数对应的列必须是可转为float的数值类型,尝试将包含序列的列转为float时就会触发该错误。

对比正常运行的代码,denNet、denPoints等变量应为单个数值,因此生成的DataFrame列是数值类型,能被lmplot正常处理。

解决方法

  • 提取单个数值而非序列:如果miaFG、miaWin等变量是从其他DataFrame提取的Series,确保用.iloc[0]或.values[0]取出单个数值,而非保留Series/数组类型。示例:
    # 假设从某DataFrame提取数据,修正为取单个值
    miaFG = some_dataframe['Field Goal Percentage'].iloc[0]
    miaWin = some_dataframe['Wins'].iloc[0]
    
  • 验证变量类型:构建DataFrame前,用type()函数检查数值变量类型,确认输出为<class 'float'>或<class 'int'>。例如:print(type(miaFG))。
  • 改用字典构建DataFrame:这种方式更直观,可避免序列混入数值列:
    east_fg_df = pd.DataFrame({
        'Teams': ["Heat", "Knicks", "Celitcs", "76ers"],
        'Field Goal Percentage': [miaFG, nykFG, bosFG, phiFG],
        'Wins': [miaWin, nykWin, bosWin, phiWin]
    })
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 03:45:01