简体   繁体   中英

Issues with concatenation in multi-dimensional arrays in Python

I am trying to concatenate A with C1 and C2 . For C1=[] , I am not sure why there is an extra [0] in B1 . For C2=[1,2] , there is a shape mismatch. The current and the desired outputs are attached. I am interested in the following conditions:

(1) If C1=[] , no need to insert A1 in B1 . (2) If C1=[1] , insert A1 for the specific position in B1 . (3) If C1=[1,2] , insert A1 for all the specific positions in B1 .

import numpy as np
A=np.array([[[1],
        [2],
        [3],
        [4],
        [5],
        [6],
        [7]]])
C1=[]
C2=[1,2]
D=[7]
A1=np.array([0])
A2=np.array([0])

B1=np.insert(A,C1+D,[A1,A2],axis=1)
print("B1 =",[B1])

B2=np.insert(A,C2+D,[A1,A2],axis=1)
print("B1 =",[B2])

The current output is

B1 = [array([[[1],
        [2],
        [3],
        [4],
        [5],
        [6],
        [7],
        [0],
        [0]]])]


in <module>
    B2=np.insert(A,C2+D,[A1,A2],axis=1)

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

  File "C:\Users\USER\anaconda3\lib\site-packages\numpy\lib\function_base.py", line 4678, in insert
    new[tuple(slobj)] = values

ValueError: shape mismatch: value array of shape (2,1)  could not be broadcast to indexing result of shape (3,1,1)

The desired output is

B1 = [array([[[1],
        [2],
        [3],
        [4],
        [5],
        [6],
        [7],
        [0]]])]

B2 = [array([[[1],
        [0],
        [0],
        [2],
        [3],
        [4],
        [5],
        [6],
        [7],
        [0]]])]

insert is a Python function. It's arguments are evaluated in full before being passed to it. Look at what you are passing:

In [20]: C1+D, C2+D
Out[20]: ([7], [1, 2, 7])

In [21]: np.array([A1,A2])
Out[21]: 
array([[0],
       [0]])

You have lost the imagined [],[7] and [[1,2],[7]] structure.

Your B1 successfully puts the [[0],[0]] at slot 7. B2 fails because there are 3 slots, but 2 values.

Here's what your A1 inserts are doing (the axis=1 isn't important here):

In [22]: np.insert(A,C1,A1)
Out[22]: array([1, 2, 3, 4, 5, 6, 7])

In [23]: np.insert(A,C2,A1)
Out[23]: array([1, 0, 2, 0, 3, 4, 5, 6, 7])

Since A1 is a (1,) shape, it can broadcast to match the shape of the (0,) C1 and (2,) C2 .

If you want two 0's together you'll need one of:

In [25]: np.insert(A,[1],[0,0])
Out[25]: array([1, 0, 0, 2, 3, 4, 5, 6, 7])

In [26]: np.insert(A,[1,1],[0])
Out[26]: array([1, 0, 0, 2, 3, 4, 5, 6, 7])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM