【问题标题】:How do I re-insert deleted array elements in the correct position?如何在正确的位置重新插入已删除的数组元素?
【发布时间】:2022-01-12 07:54:12
【问题描述】:

我需要在数组中重新插入以前删除的元素。在这种情况下,我需要在修复一组参数后最小化一组参数的损失函数。最小化器只取剩余的未固定子集,但我需要将整个参数集传递给要最小化的函数。

我想过使用 np.delete 和要排除的元素的索引,然后使用 np.insert 以相同的逻辑撤消它,但是由于 np.insert 和 np.delete 在中不对称,以下方法不起作用他们是如何运作的:

import numpy as np
pars = np.array([0,10,20,30,40,50])
exclude = [1,3] # index of elements to exclude

parsSubset = np.delete(pars,exclude)
excludedPars = pars[exclude]
parsRecreated = np.insert(parsSubset,exclude,excludedPars)
print(parsRecreated)

此类代码的输出为[ 0 10 20 40 30 50]

我在下面提供了我的解决方案,但我想知道我是否缺少更优雅的解决方案

【问题讨论】:

  • 当元素被删除时,数组真的“讨厌”......也许你需要一个列表?
  • 虽然我讨厌列表 :) ...这里的问题是 np.delete 不像 np.insert 那样“按顺序”工作,也就是说,它一次删除所有元素。跨度>
  • 运气不好。如果你看到了一个解决方案,但你决定不喜欢它使用的结构......
  • 带有列表的代码看起来如何?

标签: python arrays numpy


【解决方案1】:

这是我的解决方案,创建一个掩码并使用它重新插入:

import numpy as np
pars = np.array([0,10,20,30,40,50])
exclude = [1,3] # index of elements to exclude
mask = np.array([True] * pars.size)
mask[exclude] = False

parsSubset = pars[mask] 
parsRecreated = np.zeros(pars.size)
parsRecreated[mask] = parsSubset
parsRecreated[~mask] = pars[~mask]
print(parsRecreated)

【讨论】:

    【解决方案2】:
    In [24]: pars = np.array([0,10,20,30,40,50])
        ...: exclude = [1,3] # index of elements to exclude
        ...: 
        ...: parsSubset = np.delete(pars,exclude)
    In [25]: pars
    Out[25]: array([ 0, 10, 20, 30, 40, 50])
    In [26]: parsSubset
    Out[26]: array([ 0, 20, 40, 50])
    In [27]: np.insert(parsSubset,exclude,100)
    Out[27]: array([  0, 100,  20,  40, 100,  50])
    

    deletepars 中删除这些项目:

    In [33]: pars[exclude]
    Out[33]: array([10, 30])
    

    insertparsSubset这些项目之前添加项目:

    In [34]: parsSubset[exclude]
    Out[34]: array([20, 50])
    

    insert 适用于当前数组,而不是目标数组。在内部,它确实考虑到一旦在20 之前插入了一个项目,嵌套插入点就会移动。其实它的代码中有一行

    indices[order] += np.arange(numnew)
    

    我们可以用自己的减法来弥补:

    In [36]: np.insert(parsSubset,exclude-np.arange(2),100)
    Out[36]: array([  0, 100,  20, 100,  40,  50])
    

    deleteinsert 在内部很复杂,因为它们可以处理不同的维度和不同类型的输入(标量、切片、序列)。但是对于这样的序列,两者都可以像您一样使用掩码。您的解决方案没有任何问题,而且很可能更快(没有一般开销)。

    【讨论】:

    • 谢谢,我喜欢 np.arange 解决方案,它应该推广到 np.arange(len(exclude)) 这就是我错过的。你用紧凑性来换取可读性我想我的解决方案
    猜你喜欢
    • 1970-01-01
    • 2018-03-13
    • 2012-08-03
    • 2014-12-27
    • 1970-01-01
    • 2012-09-28
    • 2020-01-16
    相关资源
    最近更新 更多