I have a list A
containing a numpy array. I want to insert element C1
at specific positions in A
according to J
. But I am getting an error. I have included the expected output.
import numpy as np
J=[[4, 7, 10]]
C1=[0]
A=[np.array([10. , 0.6382821834929432 , 0.5928417218382795 ,
0.5542698411479658 , 0.6677634679746701 , 0.8578897621707481 ,
0.6544597670890333 , 0.32706383813570833, 0.8966468940380192 ])]
A=np.insert(A[0],J,[C1],axis=1)
The error is
in <module>
A=np.insert(A[0],J,[C1],axis=0)
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
A=[np.array([10. , 0.6382821834929432 , 0.5928417218382795 ,
0.5542698411479658 , 0, 0.6677634679746701 , 0.8578897621707481 ,
0, 0.6544597670890333 , 0.32706383813570833, 0, 0.8966468940380192 ])]
CodePudding user response:
It works like this:
import numpy as np
# need to take the indices based on the array before anything is inserted
J = [[4, 6, 8]]
C1 = [0]
A = [np.array([10. , 0.6382821834929432 , 0.5928417218382795 ,
0.5542698411479658 , 0.6677634679746701 , 0.8578897621707481 ,
0.6544597670890333 , 0.32706383813570833, 0.8966468940380192 ])]
A = np.insert(A[0], J[0], C1[0])
Output A
:
array([10. , 0.63828218, 0.59284172, 0.55426984, 0. ,
0.66776347, 0.85788976, 0. , 0.65445977, 0.32706384,
0. , 0.89664689])
Notice that A is not a list with a np.array
anymore, it is just the np.array
now.
EDIT insert one at a time with given indices.
J = [[4, 7, 10]]
C1 = [0]
A = [np.array([10. , 0.6382821834929432 , 0.5928417218382795 ,
0.5542698411479658 , 0.6677634679746701 , 0.8578897621707481 ,
0.6544597670890333 , 0.32706383813570833, 0.8966468940380192 ])]
for elem in J[0]:
A = [np.insert(A[0], elem, C1[0])]