python - 将另一个 numpy 数组作为数组附加到 numpy 数组,而不是它的元素

标签 python arrays python-3.x numpy

我想创建一个数组的数组,但是当我使用 np.append 时如果它们的元素我得到列表:

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

这就是我得到的:

In: image_batches

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

这就是我需要的:

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

我通过使用实现了这一点

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

但也许有更优雅的方法来做到这一点?

最佳答案

就像 @hpaulj 在评论中提到的,您可以直接使用高级索引:

im_data[np.array(batches)]

输出:

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

关于python - 将另一个 numpy 数组作为数组附加到 numpy 数组,而不是它的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63124790/

相关文章:

python - 计算嵌套列表中的唯一元组

python - Wheel 是对另一个 Python 的引用

c - 使用C中的函数查找数组中的最大值和最小值

python - 带有状态码 200 重定向的链接

python - ValueError : Layer sequential expects 1 inputs, 但它在 tensorflow 2.0 中收到了 211 个输入张量

python - python中如何移动到下一个文件

python - 迭代器对象、PyCapsules 和内存性能

python - 在 Python 中使用 ARN iam 将文件上传到 Amazon s3 存储桶

java - 如何使用数组在java中使用素数对数字进行编码?

ios - 我如何在 UIImageView 中使用一串图像名称?