Home > Software design >  Inserting multiple elements into an array in one step
Inserting multiple elements into an array in one step

Time:06-21

I have an array B with shape (1,7,1). I am trying to insert multiple elements (here, 2 elements) at specific positions in one step. The shape of the new array B3 should be (1,9,1). However, I am getting an error.

import numpy as np

B = np.array([[[0.678731133],
        [1.244425627],
        [0.767884084],
        [2.006154222],
        [3.073758392],
        [1.037728999],
        [5.032947535]]])
B1=np.array([10])
B2=np.array([20])
B3=np.insert(B, 2, B1,8,B2,axis=1)
print("B3=",[B3])
print("B3 shape=",[B3.shape])

The error is

<module>
    B3=np.insert(B, 2, B1,8,B2,axis=1)

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

TypeError: _insert_dispatcher() got multiple values for argument 'axis'

The desired output is

B3 = np.array([[[0.678731133],
        [1.244425627],
        [10],
        [0.767884084],
        [2.006154222],
        [3.073758392],
        [1.037728999],
        [5.032947535],
        [20]]])
B3 shape= (1,9,1)

CodePudding user response:

B3=np.insert(B, [2,7],[B1,B2],axis=1) works. You can check np.insert documentation

print(B3)
print(B3.shape)
>>>[[[ 0.67873113]
  [ 1.24442563]
  [10.        ]
  [ 0.76788408]
  [ 2.00615422]
  [ 3.07375839]
  [ 1.037729  ]
  [ 5.03294753]
  [20.        ]]]
>>>(1, 9, 1)

CodePudding user response:

Slicing and horizontal stacking also works

np.hstack([B[:, :2], [[B1]], B[:, 2:], [[B2]]])

#array([[[ 0.67873113],
#        [ 1.24442563],
#        [10.        ],
#        [ 0.76788408],
#        [ 2.00615422],
#        [ 3.07375839],
#        [ 1.037729  ],
#        [ 5.03294753],
#        [20.        ]]])
  • Related