numpy数组:不选择特定的行或列

时间:2019-06-19 09:13:05

标签: python numpy numpy-slicing

我有一个简单的numpy数组。我想选择第一行和第六行以外的所有行 我尝试过:

temp = np.array([1,2,3,4,5,6,7,8,9])
t = temp[~[0,5]]

我收到以下错误:

 TypeError: bad operand type for unary ~: 'list'

正确的方法是什么?

3 个答案:

答案 0 :(得分:0)

您不能以这种方式创建索引。相反,您可以创建从0到temp.size的数字范围并删除不需要的索引:

In [19]: ind = np.delete(np.arange(temp.size), [0, 5])

In [21]: temp[ind]
Out[21]: array([2, 3, 4, 5, 7, 8, 9])

或仅按如下所示创建它:

In [16]: ind = np.concatenate((np.arange(1, 5), np.arange(6, temp.size)))

In [17]: temp[ind]
Out[17]: array([2, 3, 4, 5, 7, 8, 9])

答案 1 :(得分:0)

您可以使用 numpy.delete 删除特定索引位置的元素:

t = np.delete(temp, [0, 5])

或者您可以创建一个布尔数组,从而可以求反索引:

bool_idx = np.zeros(len(temp), dtype=bool)
bool_idx[[0, 5]] = True
t = temp[~bool_idx]

答案 2 :(得分:-1)

您可以使用np.r_ numpy对象,该对象通过使用给出结果输出的索引将它们分成多个数组,从而将其串联起来。

np.r_[temp[1:5], temp[6:]]

上面的代码将从原始数组中切出的两个数组连接在一起,因此没有指定索引的结果数组也将连接起来。