0

I have the following ndarray:

array([[0.00000, 0.00000,  50.00000],
       [0.00000, 10.02227, 50.00000],
       [0.00000, 20.04454, 50.00000],
       [0.00000, 30.06682, 50.00000],
       [0.00000, 40.08909, 50.00000]])

and I would like to transform each row into a separate ndarray in order to have a nested ndarray structure:

array([[array([0.00000, 0.00000,  50.00000])],
       [array([0.00000, 10.02227, 50.00000])],
       [array([0.00000, 20.04454, 50.00000])],
       [array([0.00000, 30.06682, 50.00000])],
       [array([0.00000, 40.08909, 50.00000])]])

I've tried with:

new_array = numpy.apply_along_axis(np.array, 1, old_array)

but did not succeed because new_array is equal to old_array.

How can I transform my array? I guess there should be a solution using a for cycle, but is there a more pythonic alternative?

fma
  • 219
  • 2
  • 14
  • Note that working with arrays of array object is generally far less inefficient. – Jérôme Richard Jun 09 '22 at 21:52
  • Did you mean far less efficient? – fma Jun 10 '22 at 08:20
  • It should be significantly slower (and also take more memory space regarding the actual shape). – Jérôme Richard Jun 10 '22 at 08:41
  • What is a more efficient alternative? A list of arrays? And in case I want to have a 2D array of array objects, should I prefer a list of list of array objects? – fma Jun 10 '22 at 08:44
  • 1
    ND arrays are generally fast as long as you work on *native types*. If you work on object, then all alternatives are slow (because of the CPython interpreter) but I think lists should be faster in that case (list of lists). Numpy array can be used for convenience but not speed in such a case. Related post: [Why is `np.sum(range(N))` very slow?](https://stackoverflow.com/questions/69584027). – Jérôme Richard Jun 10 '22 at 12:10

1 Answers1

1

Not sure why you want to achieve this, as a list of np.array makes more sense, but you could do this:

new_array = np.zeros((old_array.shape[0], 1), dtype = 'O')
new_array[:] = [[x] for x in old_array]
new_array

output:

array([[array([ 0.,  0., 50.])],
       [array([ 0.     , 10.02227, 50.     ])],
       [array([ 0.     , 20.04454, 50.     ])],
       [array([ 0.     , 30.06682, 50.     ])],
       [array([ 0.     , 40.08909, 50.     ])]], dtype=object)
Z Li
  • 4,133
  • 1
  • 4
  • 19
  • Thanks! I want to have a 2D `np.array` where each element is a 1x3 `np.array`, representing xyz coordinates. Does this make sense in your opinion or a list of list of `np.array` would be better? – fma Jun 10 '22 at 08:27
  • 1
    @fma: why not simply use a 3D array of shape (m, n, 3)? – Stef Jun 10 '22 at 15:21
  • That's definitely an option, thanks – fma Jun 13 '22 at 07:49