繁体   English   中英

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

[英]Deleting multiple elements at once from a numpy 2d array

当我有索引时,有没有办法从 numpy 二维数组中删除? 例如:

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]
    ]

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

这是转换索引并使用它的方法

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)

对于重塑,您应该删除项目,以便在删除后会有相同数量的项目和行和列

Numpy 不知道当您给它提供这样的任意索引时,您每行只删除一个元素。 既然你知道这一点,我建议使用掩码来缩小数组。 屏蔽也有同样的问题:它不对结果的形状做任何假设(因为它通常不能),并返回一个 raveled 数组。 不过,您可以很容易地恢复您想要的形状。 事实上,我建议完全删除每个索引的第一个元素,因为每行都有一个:

 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)

这是使用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.]])

正如文件所说

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

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

其次 np.delete 期望 int 或 ints 数组作为参数,而不是元组列表。

您需要指定要求是什么。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM