我有一个简单的 numpy 数组。我想选择除第 1 行和第 6 行之外的所有行:
temp = np.array([1,2,3,4,5,6,7,8,9])
t = temp[~[0,5]]
我收到以下错误:
TypeError: bad operand type for unary ~: 'list'
这样做的正确方法是什么?
我有一个简单的 numpy 数组。我想选择除第 1 行和第 6 行之外的所有行:
temp = np.array([1,2,3,4,5,6,7,8,9])
t = temp[~[0,5]]
我收到以下错误:
TypeError: bad operand type for unary ~: 'list'
这样做的正确方法是什么?
您可以使用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]
您不能以这种方式创建索引。相反,您可以创建一个从 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])
您可以使用np.r_ numpy 对象,该对象通过使用给出结果输出的索引来分解它们来连接数组。
np.r_[temp[1:5], temp[6:]]
上面的代码连接了从原始数组中分割出来的两个数组,因此得到了没有指定索引的结果数组。