Reading:Numpy error – ValueError: setting an array element with sequence

Numpy error – ValueError: setting an array element with sequence

You have struggled during hours and hours to understand why you got this damned error while compiling a complex array structure? I did. In my case I was trying to create an array of the following shape :

[  [ [0,0,1,0] , 0.5] , [ [0,1,1,0] , 0.3] , [ [1,0,1,0] , 0.2] ]

With the basic syntax, it was impossible. I first didn’t notice the problem because I wasn’t using the ‘array‘ constructor, but when I tried to append some value to my initial vector, I got the error : ValueError: setting an array element with sequence.

Even the simple construction : array([( [0,0,1,0],0.5)]) would give the error.

the problem is that numpy is made to calculate vectors and arrays. It doesn’t like the fact you give it table with different sizes. Ok, then you can try to change the second value 0.5 to [0.5,0,0,0]. It would work…. but it’s not really clean. Your code will look messy.

Instead, here is the solution I found after 4 hours looking everywhere on the web… finding nothing. This is my own solution, so if helped you, I would be very glad :-D

In order to help numpy to accept your vector… tell it it’s not a vector :

array([( [0,0,1,0],0.5)],object)

By doing this you change de dtype of your array, and it can accept even personnal classes.

Does that work for you?