1

I have two arrays P and J. I want to insert C1=nan in P according to positions in J. But I am getting an error. I present the expected output.

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])

The error is

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

The expected output is

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]])

3 Answers 3

1

You can use for loop to reach each item in J.

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

for i in J[0]:
    P = np.insert(P, i, [C1], axis=1)
print("Pnew =", [P])
Sign up to request clarification or add additional context in comments.

Comments

1

You need to pass J.ravel() and C1 as value not list.

np.insert(P,J.ravel(),C1,axis=1)

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

If you want to get the exactly desired output, you need to set (1,3,3,4) for J.

>>> np.insert(P,(1,3,3,4),C1,axis=1)
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]])

Comments

0
import numpy as np

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]])

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.