valueerror: all input arrays must have same dimensions – Code Example

Total
0
Shares

Get Python code to resolve valueerror: all the input arrays must have same number of dimensions. The error occurs when you do operations like numpy.append() on two arrays of incompatible dimensions.

The format of append() is –

numpy.append(arr, values, axis=None)

According to numpy documentation –

These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis). If axis is not specified, values can be any shape and will be flattened before use.

So, if the shape of values is not same as arr then Python will throw valueerror: all input arrays must have same dimensions.

This error is similar to this problem – Input array dimensions except concatenation axis must match.

Code Example

Error Code – Let’s first reproduce the error –

import numpy as np
np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0)

This will throw the error –

Traceback (most recent call last):
    ...
ValueError: all the input arrays must have same number of dimensions, but
the array at index 0 has 2 dimension(s) and the array at index 1 has 1
dimension(s)

It is because the first array is of 2 dimensions while second array is of 1 dimension.

Solution

1. Use same dimensions –

import numpy as np
np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)

Output –

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

Notice that we have used [[ in second array. This made the array of 2 dimensions.

2. Use column_stack() or row_stack() functions –

import numpy as np

np.column_stack([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

Output –

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

Note that we passed a single array as parameter to column_stack function.

3. Use hstack() and vstack()

import numpy as np

np.vstack(([[1, 2, 3], [4, 5, 6]],[7, 8, 9]))

Output –

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

Live Demo

Open Live Demo