numpy切片选择数组的部分

时间:2013-10-20 12:35:54

标签: python arrays numpy

我有一个一维数组,我想从中创建一个新数组,其中只包含前者的开头,中间和结尾的用户所需大小的部分。

import numpy
a = range(10)
a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

我希望b等于:

b
array([0, 1, 2, 5, 6, 7, 9])

假设b由[:3],[5:6]和[9]的串联构成。 我当然可以使用诸如np.concatenate之类的东西,但有没有办法用切片方法或其他任何东西来做到这一点?

2 个答案:

答案 0 :(得分:1)

一种方法是使用以下命令创建要为数组建立索引的索引数组:

import numpy
a = numpy.arange(10)
i = numpy.array([0, 1, 2, 5, 6, 7, 9])  # An array containing the indices you want to extract
print a[i]  # Index the array based on the indices you selected

输出

[0 1 2 5 6 7 9]

答案 1 :(得分:0)

我找到了解决方案:

import numpy as np
a = range(10)
b = np.hstack([a[:3], a[5:6], a[9])
b
array([0, 1, 2, 5, 6, 7, 9])

但切片是否允许这样的举动?