65

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Olivier_s_j
  • 5,490
  • 24
  • 80
  • 126

4 Answers4

81

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.

Georgy
  • 12,464
  • 7
  • 65
  • 73
user4815162342
  • 141,790
  • 18
  • 296
  • 355
  • 6
    To convert that array to 1D array, you can also use squeeze() – lib Feb 19 '15 at 11:22
  • Even simpler (and more accurate), instead of len(a) use: a.size – Ari Jan 15 '20 at 08:56
  • @Ari Why more accurate? `size` is documented to return the number of elements in the array, which seems to me like the exact same thing as `len()` returns. – user4815162342 Jan 15 '20 at 09:34
  • len(a) gives the "length" along one axis only. For multi-dimensional arrays (2D and above) it is better to use 'size'. – Ari Jan 21 '20 at 13:19
  • 1
    @Ari Oh, now I see what you mean: `size` is the product of lengths across dimensions. Using `a.size` makes the recipe correctly reshape arrays with more than two dimensions, where using `len` would fail with "total size of new array must be unchanged". Thanks for the hint, I've now updated the answer. – user4815162342 Jan 21 '20 at 13:33
  • `.squeeze()` is probably the most correct choice in this situation. – LudvigH Jan 12 '21 at 09:32
11

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.

Shaishav Jogani
  • 2,111
  • 3
  • 23
  • 33
Sandip Kumar
  • 129
  • 2
  • 11
4

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

jelde015
  • 554
  • 6
  • 7
3

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

user4815162342
  • 141,790
  • 18
  • 296
  • 355
NoSuchUserException
  • 700
  • 1
  • 9
  • 18