从numpy二维数组一次删除多个元素

时间:2019-09-29 13:01:46

标签: python numpy

有索引时,是否可以从numpy 2d数组中删除?例如:

a = np.random.random((4,5))
idxs = [(0,1), (1,3), (2, 1), (3,4)]

我想删除上面指定的索引。我尝试过:

np.delete(a, idxs)

但是它只是删除第一行。

举个例子,对于以下输入:

    [
        [0.15393912, 0.08129568, 0.34958515, 0.21266128, 0.92372852],
        [0.42450441, 0.1027468 , 0.13050591, 0.60279229, 0.41168151],
        [0.06330729, 0.60704682, 0.5340644 , 0.47580567, 0.42528617],
        [0.27122323, 0.42713967, 0.94541073, 0.21462462, 0.07293321]
    ]

并使用上述索引,我希望结果为:

    [
        [0.15393912, 0.34958515, 0.21266128, 0.92372852],
        [0.42450441, 0.1027468 , 0.13050591, 0.41168151],
        [0.06330729, 0.5340644 , 0.47580567, 0.42528617],
        [0.27122323, 0.42713967, 0.94541073, 0.21462462]
    ]

4 个答案:

答案 0 :(得分:2)

您的索引应该用于平面数组,否则只能删除行或列。

这里是转换索引和使用索引的方法

arr = np.array([
    [0.15393912, 0.08129568, 0.34958515, 0.21266128, 0.92372852],
    [0.42450441, 0.1027468 , 0.13050591, 0.60279229, 0.41168151],
    [0.06330729, 0.60704682, 0.5340644 , 0.47580567, 0.42528617],
    [0.27122323, 0.42713967, 0.94541073, 0.21462462, 0.07293321]
])

idxs = [(0,1), (1,3), (2, 1), (3,4)]

idxs = [i*arr.shape[1]+j for i, j in idxs]

np.delete(arr, idxs).reshape(4,4)

要进行重塑,应删除项目,以使删除后的项目以及行和列的数量相等

答案 1 :(得分:0)

当给像这样的任意索引时,Numpy并不知道每行要删除一个元素。既然您知道这一点,我建议您使用遮罩来缩小阵列。遮罩也有同样的问题:它不对结果的形状做任何假设(因为它通常无法做到),而是返回一个混乱数组。您可以很轻松地恢复想要的形状。实际上,我建议完全删除每个索引的第一个元素,因为每行有一个:

 def remove_indices(a, idx):
     if len(idx) != len(idx): raise ValueError('Wrong number of indices')
     mask = np.ones(a.size, dtype=np.bool_)
     mask[np.arange(len(idx)), idx] = False
     return a[mask].reshape(a.shape[0], a.shape[1] - 1)

答案 2 :(得分:0)

这是使用np.where

的方法
import numpy as np
import operator as op

a = np.arange(20.0).reshape(4,5)
idxs = [(0,1), (1,3), (2, 1), (3,4)]

m,n = a.shape

# extract column indices
# there are simpler ways but this is fast
columns = np.fromiter(map(op.itemgetter(1),idxs),int,m)

# build decimated array
result = np.where(columns[...,None]>np.arange(n-1),a[...,:-1],a[...,1:])

result
# array([[ 0.,  2.,  3.,  4.],
#        [ 5.,  6.,  7.,  9.],
#        [10., 12., 13., 14.],
#        [15., 16., 17., 18.]])

答案 3 :(得分:-1)

如文档所述

  

返回一个删除了沿轴的子数组的新数组。

np.delete根据参数轴的值删除行或列。

第二,np.delete将int或int数组作为参数而不是元组列表。

您需要指定要求。

@divakar建议在Stackoverflow上查看有关删除numpy数组中单个项目的其他答案。