【问题标题】:Numpy array : NOT select specific rows or columnsNumpy数组:不选择特定的行或列
【发布时间】:2019-11-01 23:34:01
【问题描述】:

我有一个简单的 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'

这样做的正确方法是什么?

【问题讨论】:

标签: python numpy numpy-slicing


【解决方案1】:

您可以使用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】:

    您可以使用np.r_ numpy 对象,该对象通过使用给出结果输出的索引将数组拆分为数组。

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

    上面的代码连接了从原始数组中分割出来的两个数组,因此结果数组没有指定索引。

    【讨论】:

      【解决方案3】:

      您不能那样创建索引。相反,您可以创建从 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])
      

      【讨论】:

        猜你喜欢
        • 2014-05-20
        • 2023-03-29
        • 1970-01-01
        • 2015-01-14
        • 2016-07-21
        • 2017-11-06
        • 1970-01-01
        • 2022-11-01
        相关资源
        最近更新 更多