1

what's the problem with creating this numpy array

np.array( [np.array([1]), np.array([ [1,2] ])] )

# Error: could not broadcast input array from shape (2) into shape (1)

but no problem with this

np.array( [np.array([1]), np.array([ [1,2], [1,2] ])] )

what's the problem with creating a container array for different things with different shapes?

7
  • In both cases np.array is fudging. In the second it makes a 2 element object array, with (1,) and (2,2) arrays. In the first the combination of (1,) and (1,2) takes a different path and ends in an error. Commented Oct 14, 2019 at 13:57
  • This is not a reliable way of making an object array with an arbitrary mix of inputs. Commented Oct 14, 2019 at 14:57
  • See stackoverflow.com/questions/26885508/… for a more detailed explanation. And stackoverflow.com/questions/49117632/… Commented Oct 14, 2019 at 15:55
  • @hpaulj what's problem with creating array of some different things in numpy? Commented Oct 15, 2019 at 11:55
  • Read the duplicates Commented Oct 15, 2019 at 12:03

1 Answer 1

0

If the final output can be a 1D vector, np.append might do the trick:

np.append(np.array([1]),np.array([[1,2]]))

If each element of the final desired array is a different dimension, do you need it to be a numpy object? a list should work final = [np.array([1]), np.array([ [1,2], [1,2] ])]

Sign up to request clarification or add additional context in comments.

2 Comments

can you explain what's the problem with creating that array with np.array ?
numpy is trying to bring n-dimension matrix operations to python. so results[1,4,5] returns some number. Arrays must be a rectangle (2d), box (3d), n-rectangle (n-dim). When you try to combine arrays with a different shape, its like you're trying to make a box with a sheet of 1x1" paper and a 2x2'' box. They don't make a continuous object. in your example, if numpy were to allow you, what would results[1,2] mean?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.