Home > OS >  Appending multi-dimensional arrays of different shapes in Python
Appending multi-dimensional arrays of different shapes in Python

Time:06-20

Arrays C1 and C2 have shapes (1, 2, 2) and (1, 1, 2) respectively. I want to append these arrays into a new array C3. But I am getting an error. The desired output is attached.

import numpy as np

arC1 = []
arC2 = []

C1=np.array([[[0, 1],[0,2]]])
arC1.append(C1)
C2=np.array([[[1,1]]])
C2.shape
arC2.append(C2)

C3=np.append(C1,C2,axis=0)

The error is

 <module>
    C3=np.append(C1,C2,axis=0)

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

  File "C:\Users\USER\anaconda3\lib\site-packages\numpy\lib\function_base.py", line 4745, in append
    return concatenate((arr, values), axis=axis)

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

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 2 and the array at index 1 has size 1

The desired output is

C3[0]=np.array([[[0, 1], [0, 2]]])
C3[1]=np.array([[2,3]])

CodePudding user response:

C1 = np.array([[[0, 1],[0,2]]])
print(C1.shape)  # (1, 2, 2)
C2 = np.array([[[1,1]]])
print(C2.shape)  # (1, 1, 2)

If you run

C3 = np.append(C1,C2,axis=1)
print(C2.shape)  # (1, 3, 2)

It means like this. (1, 2, 2) (1, 1, 2) = (1, 3, 2)

If you run

C3 = np.append(C1,C2,axis=0)

It means like this. (1, 2, 2) (1, 1, 2) = (2, ??, 2)

Since numpy is a matrix, it can't be added because the lower dimensions are different.


Simply, when you set axis parameter value at append function for append two arrays, the values of all dimensions shall be the same except for the values of the dimensions corresponding to the axis

example 1

C1 = np.array([[[[[0, 1]]],[[[0, 2]]], [[[0, 2]]]]])
C2 = np.array([[[[[1]]],[[[2]]], [[[3]]]]])
C3 = np.append(C1, C2, axis=4)

and if the dimensions are as follows,

(1, 3, 1, 1, 2)  # C1
(1, 3, 1, 1, 1)  # C2

-->
(1, 3, 1, 1, 3)  # C3

Only axis 4 dimmension is different so you can do np.append(C1, C2, axis=4)

example 2

C1 = np.array([[[[[0, 1]]],[[[0, 2]]], [[[0, 2]]]]])
C2 = np.array([[[[[1, 1]]],[[[2, 2]]], [[[3, 3]]]], [[[[1, 1]]],[[[2, 2]]], [[[3, 3]]]]])
C3 = np.append(C1, C2, axis=0)

and if the dimensions are as follows,

(1, 3, 1, 1, 2)  # C1
(2, 3, 1, 1, 2)  # C2

-->
(3, 3, 1, 1, 2)  # C3

Only axis 0 dimmension is different so you can do np.append(C1, C2, axis=0)

example 3

C1 = np.array([[[[[0, 1]]],[[[0, 2]]], [[[0, 2]]]]])
C2 = np.array([[[[[1]]],[[[2]]], [[[3]]]], [[[[1]]],[[[2]]], [[[3]]]]])

and if the dimensions are as follows,

(1, 3, 1, 1, 2)  # C1
(2, 3, 1, 1, 1)  # C2

-->
ERROR

Except for the Axis value you specify, at least one dimension is more different. So it's impossible to set axis parameter with these arrays.

  • Related