Skip to content
Advertisement

insert column into array using scaler obj (numpy.insert)

    import numpy as np
    a = np.array([[1, 6], [2, 7], [3, 8]])
    print(a,'n')
    c2 = np.insert(a, [1], [[9],[99],[999]], axis=1)
    print(c2,'n')
    c3 = np.insert(a, 1, [9,99,999], axis=1)
    print(c3,'n')
    c4 = np.insert(a, 1, [[9],[99],[999]], axis=1)
    print(c4,'n')
    c5 = np.insert(a, [1], [9,99,999], axis=1)
>>>the result:
[[1 6]
 [2 7]
 [3 8]]

c2 = 
[[  1   9   6]
 [  2  99   7]
 [  3 999   8]]

c3 = 
[[  1   9   6]
 [  2  99   7]
 [  3 999   8]] 

c4 = 
[[  1   9  99 999   6]
 [  2   9  99 999   7]
 [  3   9  99 999   8]]

c5 = 
[[  1   9  99 999   6]
 [  2   9  99 999   7]
 [  3   9  99 999   8]]

why C4 did not take column value and insert it before each item in column 1 i think it should be [[ 1 9 6][ 2 99 7][ 3 999 8]]

also

a = np.array([[1, 6], [5, 2]])
print(a,'n')

c4 = np.insert(a, 1, [[9,88],[99,66]], axis=1)
print(c4,'n')

why the result is equal to

[[ 1  9 99  6]
 [ 5 88 66  2]]

not equal to

[[ 1  9 88  6]
 [ 5 99 66  2]]

while the insert axis along axis 0 will inserted normally

c11 = np.insert(a, 1, [9,99], axis=0)
print(c11,'n')
c12 = np.insert(a, 1, [[9],[99]], axis=0)
print(c12,'n')

the result:

[[ 1  6]
 [ 9 99]
 [ 2  7]
 [ 3  8]] 

[[ 1  6]
 [ 9  9]
 [99 99]
 [ 2  7]
 [ 3  8]]

Advertisement

Answer

after searching we found the answer as below:

the output of scaler index was 1d array

a = np.array([[1, 6], [2, 7], [3, 8]])
print(a)
print(a[:,1])
print(a[:,[1]])
    
>>> 
a
[[1 6]
 [2 7]
 [3 8]]

a[:,1]
 [6 7 8]

a[:,[1]]
 [[6]
 [7]
 [8]]

so when using scaler index to insert column along axis 1, the values will be assigned for scaler output (1d array) , then transpose the scaler output values to fit the indexed column.

a = np.array([[1, 6], [5, 2]])
print(a,'n')

c4 = np.insert(a, 1, [[9,88],[99,66]], axis=1)
print(c4,'n')

a[:,1]

a[:,1] = [a01 a11] = [[9  88]
                     [99 66]]

so the

a01 = [[9 ]      a11 = [[88]
       [99]]            [66]]

after that a[:,1] will be transposed to fit with column

[[ 1  9 99  6]
 [ 5 88 66  2]]

while when using scaler index to insert column along axis 1, the scaler output will fit row index,

a = np.array([[1, 6], [2, 7], [3, 8]])
c11 = np.insert(a, 1, [9,99], axis=0)
print(c11,'n')
c12 = np.insert(a, 1, [[9],[99]], axis=0)
print(c12,'n')

a[1,:] of c11

a[1,:] = [a10 a11] = [9  99]

so the

a10 = [9]      a11 = [99]
                  

a[1,:] of c12 (the values will be broadcasting) to fit obj

a[1,:] = [a10 a11] = [[9  9 ]                         
                      [99 99]]

so the

a10 = [[9 ]      a11 = [[9 ]
       [99]]            [99]]

the result:

[[ 1  6]
 [ 9 99]
 [ 2  7]
 [ 3  8]] 

[[ 1  6]
 [ 9  9]
 [99 99]
 [ 2  7]
 [ 3  8]]
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement