Home > Software design >  Inserting an element in a multi-dimensional array in Python
Inserting an element in a multi-dimensional array in Python

Time:06-21

The shape of B is (1,7,1). I am trying to insert B1 at a specific position in B but how do I keep the shape of new array B2 same as B with an extra element i.e. (1,8,1)? The current and desired outputs are attached.

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.insert(B, 2, B1)
print("B2=",[B2])
print("B2 shape=",[B2.shape])

The current output is

B2= [array([ 0.678731133,  1.244425627, 10.000000000,  0.767884084,
        2.006154222,  3.073758392,  1.037728999,  5.032947535])]
B2 shape= [(8,)]

The desired output is

B2=np.array([[[0.678731133],
        [1.244425627],
        [0.767884084],
        [2.006154222],
        [3.073758392],
        [1.037728999],
        [5.032947535]]])

B2 shape=[(1, 8, 1)]

CodePudding user response:

The docs say: If axis is None then arr is flattened first, which explains the result you are seeing. Try telling it which axis to insert into : B2=np.insert(B, 2, B1, axis=1).

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.insert(B, 2, B1, axis=1)

print("B2=",B2)
print("B2 shape=",B2.shape)

This prints:

B2= [[[ 0.67873113]
  [ 1.24442563]
  [10.        ]
  [ 0.76788408]
  [ 2.00615422]
  [ 3.07375839]
  [ 1.037729  ]
  [ 5.03294753]]]
B2 shape= (1, 8, 1)

[Also, your desired output does not show the inserted element. I assume that's an oversight]

  • Related