What does "ValueError: object too deep for desired array" mean and how to fix it?

PythonNumpyConvolutionValueerror

Python Problem Overview


I'm trying to do this:

h = [0.2, 0.2, 0.2, 0.2, 0.2]

Y = np.convolve(Y, h, "same")

Y looks like this:

screenshot

While doing this I get this error:

ValueError: object too deep for desired array

Why is this?

My guess is because somehow the convolve function does not see Y as a 1D array.

Python Solutions


Solution 1 - Python

The Y array in your screenshot is not a 1D array, it's a 2D array with 300 rows and 1 column, as indicated by its shape being (300, 1).

To remove the extra dimension, you can slice the array as Y[:, 0]. To generally convert an n-dimensional array to 1D, you can use np.reshape(a, a.size).

Another option for converting a 2D array into 1D is flatten() function from numpy.ndarray module, with the difference that it makes a copy of the array.

Solution 2 - Python

np.convolve() takes one dimension array. You need to check the input and convert it into 1D.

You can use the np.ravel(), to convert the array to one dimension.

Solution 3 - Python

You could try using scipy.ndimage.convolve it allows convolution of multidimensional images. here is the docs

Solution 4 - Python

np.convolve needs a flattened array as one of it's inputs, you can use numpy.ndarray.flatten() which is quite fast, find it here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOlivier_s_jView Question on Stackoverflow
Solution 1 - Pythonuser4815162342View Answer on Stackoverflow
Solution 2 - PythonSandip KumarView Answer on Stackoverflow
Solution 3 - Pythonjelde015View Answer on Stackoverflow
Solution 4 - PythonNoSuchUserExceptionView Answer on Stackoverflow