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?

amin msh
  • 472
  • 5
  • 14
  • 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. – hpaulj Oct 14 '19 at 13:57
  • This is not a reliable way of making an object array with an arbitrary mix of inputs. – hpaulj Oct 14 '19 at 14:57
  • See https://stackoverflow.com/questions/26885508/why-do-i-get-error-trying-to-cast-np-arraysome-list-valueerror-could-not-broa for a more detailed explanation. And https://stackoverflow.com/questions/49117632/creating-array-of-arrays-in-numpy-with-different-dimensions – hpaulj Oct 14 '19 at 15:55
  • @hpaulj what's problem with creating array of some different things in numpy? – amin msh Oct 15 '19 at 11:55
  • Read the duplicates – hpaulj Oct 15 '19 at 12:03
  • @hpaulj is right, this is not idiomatic at all. Numpy may not be the tool for the job. – AMC Oct 16 '19 at 01:07
  • You can put those arrays in an object dtype array, but not with the `np.array` function. – hpaulj Oct 16 '19 at 02:33

1 Answers1

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] ])]

Will
  • 1,206
  • 9
  • 22
  • can you explain what's the problem with creating that array with np.array ? – amin msh Oct 15 '19 at 11:53
  • 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? – Will Oct 15 '19 at 13:41