简体   繁体   中英

Transform each row of a numpy array into a numpy array

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM