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

Python中在numpy数组指定位置插入NaN报错的问题求助

问题:NumPy数组插入nan时触发索引维度错误

场景说明

我有两个NumPy数组P和J,希望依据J中的位置在P中插入nan值,但运行代码时出现报错。

原代码

import numpy as np
from numpy import nan

J=np.array([[1, 4, 5, 7]])
P=np.array([[1.35961580e+03, 1.35179719e+03, 1.30676673e+03, 1.17569069e+02,
        5.19255443e+00, 5.19255443e+00, 5.19255443e+00, 1.00000000e-09]])
C1=nan

P=np.insert(P,J,[C1],axis=1)
print("Pnew =",[P])

错误信息

in <module>
    P=np.insert(P,J,[C1],axis=1)

  File "<__array_function__ internals>", line 5, in insert

  File "C:\Users\USER\anaconda3\lib\site-packages\numpy\lib\function_base.py", line 4626, in insert
    raise ValueError(

ValueError: index array argument obj to insert must be one-dimensional or scalar

期望输出

array([[1.35961580e+03, nan, 1.35179719e+03, 1.30676673e+03, nan, nan, 1.17569069e+02,
        nan, 5.19255443e+00, 5.19255443e+00, 5.19255443e+00, 1.00000000e-09]])

解决方法

报错核心原因是J是二维数组(形状为(1,4)),而np.insert要求索引参数必须是一维数组或标量。只需将J转换为一维数组即可,以下两种方式都可行:

  • 方式一:用flatten()扁平化数组
P = np.insert(P, J.flatten(), [C1], axis=1)
  • 方式二:直接取J的第一维元素
P = np.insert(P, J[0], [C1], axis=1)

修改后运行代码,就能得到期望的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:31:10