input array dimensions except concatenation axis match – Code Example

Total
0
Shares

In this article we will provide you Python code example to resolve valueerror: all the input array dimensions except for the concatenation axis must match exactly. This error occurs due to unmatched dimensions of arrays on which np.concatenate() is running.

Why this error is raised by Python?

This is more a mathematical error than a Python specific one. If you concatenate two matrixes, they need to have same dimensions. For example –

matrix1 = [[1, 2],
           [3, 4],
           [5, 6]]

matrix2 = [[7, 8, 9]]

We have matrix1 of dimension 3×2 and matrix2 of 1×3. There are two ways to concatenate these matrixes – On the row axis and on column axis.

If we try to concatenate over row axis, this will happen –

[[1, 2, ?],
[3, 4, ?],
[5, 6, ?],
[7, 8, 9]]

This is not acceptable to the core of mathematics. You can’t just concatenate to a row and leave all other rows without data for those extra indexes.

If we try to concatenate over column axis, then –

[[1, 2, 7],
[3, 4, 8],
[5, 6, 9]]

This is valid and acceptable.

Code Example

Error Code – Let’s first reproduce the error –

import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[7, 8]])
print(np.concatenate((a, b), axis=0))

This code will throw the valueerror: all the input array dimensions except for the concatenation axis must match exactly. Here is the complete output –

Traceback (most recent call last):
  File "concatenate_error.py", line 5, in <module>
    print(np.concatenate((a, b), axis=0))
ValueError: all the input array dimensions except for the concatenation axis must match exactly

a has 3 columns while b has 2. So, you cannot concatenate them over row (axis=0). But you can concatenate them over columns.

Solution

1. Change the dimension of b array –

import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[7, 8, 9]])
print(np.concatenate((a, b), axis=0))

Output –

[[1 2 3]
 [4 5 6]
 [7 8 9]]

2. Or, you can concatenate over axis=1 but need to transpose first –

import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[7, 8]])
print(np.concatenate((a, b.T), axis=1))

Output –

[[1 2 3 7]
 [4 5 6 8]]

Live Demo

Open Live Demo