简体   繁体   中英

Append to the numpy array another numpy array as array, not it's elements

I want to to make an array of arrays, but when I use np.append I get the list if their elements:

import numpy as np
im_data = np.array(['image0','image1','image2','image3','image4','image5','image6','image7','image8','image9','image10','image11','image12','image13','image14'])
batches = [[1,2,3,4],[7,8,9,10],[3,4,5,6]]

image_batches = []
for batch in batches:
    image_batches = np.append(image_batches,[im_data[batch]])

This is what I get:

In: image_batches

Out: array(['image1', 'image2', 'image3', 'image4', 'image7', 'image8', 'image9', 'image10', 'image3', 'image4', 'image5', 'image6'], dtype='<U32')

and this is what I need:

array([['image1', 'image2', 'image3', 'image4'], ['image7', 'image8', 'image9', 'image10'], ['image3', 'image4', 'image5', 'image6']], dtype='<U7')

I achieved this by using

image_batches = im_data[batches[0]]
for batch in batches[1:]:
    image_batches = np.vstack([image_batches, im_data[batch]])

but maybe there is more elegant way to do it?

Like mentioned by @hpaulj in comments, you can directly use advances indexing:

im_data[np.array(batches)]

output:

[['image1' 'image2' 'image3' 'image4']
 ['image7' 'image8' 'image9' 'image10']
 ['image3' 'image4' 'image5' 'image6']]

You can use list comprehension and then convert it into numpy.array :

import numpy as np
im_data = np.array(['image0','image1','image2','image3','image4','image5','image6','image7','image8','image9','image10','image11','image12','image13','image14'])
batches = [[1,2,3,4],[7,8,9,10],[3,4,5,6]]

image_batches = np.array([im_data[batch_idx] for batch_idx in batches])
image_batches

Output:

array([['image1', 'image2', 'image3', 'image4'],
       ['image7', 'image8', 'image9', 'image10'],
       ['image3', 'image4', 'image5', 'image6']], dtype='<U7')

Cheers.

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