【问题标题】:How to remove an element from an unevenly shaped array?如何从形状不均匀的数组中删除元素?
【发布时间】:2022-01-24 03:23:18
【问题描述】:
labels_1 = np.array([[-100,32,34,25,2,35,2,5,-100,-100],[-100,35,2,5,-100,-100]])
pred_1 = np.array([[8,32,3,25,2,3,2,5,8],[8,3,2,5,8]])

我想去掉labels_1中的-100,从pred_1中得到对应的索引元素。

例如输出应该是

labels_1 = np.array([[32,34,25,2,35,2,5],[35,2,5]])
pred_1 = np.array([[32,3,25,2,3,2,5],[3,2,5]])

我尝试使用np.where(labels_1!=-100),但它仅适用于具有相同长度列表的数组,但正如您所见,labels_1 中的数组具有不同的长度,这是一个问题。

【问题讨论】:

  • numpy 中没有参差不齐的数组...(注意大声警告)。
  • 该数组包含列表,实际上是列表的列表。

标签: python arrays numpy indexing filter


【解决方案1】:

我相信您正在寻找的是:

pred_1 = [[b for a, b in zip(la, lb) if a != -100] for la, lb in zip(labels_1, pred_1)]
labels_1 = [[a for a in la if a != -100] for la in labels_1]

结果:

>>> labels_1
[[32, 34, 25, 2, 35, 2, 5], [35, 2, 5]]

>>> pred_1
[[32, 3, 25, 2, 3, 2, 5], [3, 2, 5]]

正如 cmets 中所说,您不能在 numpy 中表示参差不齐的数组。如果你按照你写的那样尝试,你应该会看到一个响亮的VisibleDeprecationWarning,表明你的结果将是一个列表列表,如果你真的打算这样做,你应该指定'dtype = object'......你如果可以更好地满足您的需求,可以查看掩码数组,否则您最好使用简单列表(在本例中为列表)。

编辑

虽然有点复杂,但以下内容可能更通用(涉及ab 之一或两者的任何条件,其中ab 分别是一个数组和另一个数组的元素) :

labels_1, pred_1 = map(list, zip(*[
    list(map(list, zip(*[
        (a, b) for a, b in zip(la, lb)
        if a != -100  # you can adapt this condition at will
    ])))
    for la, lb in zip(labels_1, pred_1)
]))

这更灵活。例如,当一个数组大于另一个数组时,它可以让您选择两个数组中的元素,或者这对元素的任何条件。

【讨论】:

  • 当然——有一些事情让我很困惑:你的数组不仅参差不齐,而且它们的长度也不同。 pred_1 中可能没有“相应匹配的元素”。我错过了什么吗?
  • 您是说可能存在 len(labels_1[i]) != len(pred_1[i]) 的情况吗?这不会发生,因为这两个数组都是在同时应用于它们的相同过程之后生成的。 (如果我误解了你的问题,我很抱歉,我对 pythonic 行话 atm 不是那么精通)。再次感谢您的回答。
  • 不用担心;在您的示例中,子列表在labels_1pred_1 之间的长度确实不同:list(map(len, labels_1)) # gives [10, 6)list(map(len, pred_1)) # gives [9, 5]
【解决方案2】:

如果您的 numpy 数组中的列表大小不均,您就违背了 numpy 数组的目的,因此您可以为此使用 numpy 解决方案。

不过,您可以使用列表理解来完成此任务:

labels_1 = np.array([[x for x in y if x != -100] for y in labels_1])
pred_1 = np.array([[x for x in y if x != -100] for y in pred_1])

输出:

>>> labels_1
array([list([32, 34, 25, 2, 35, 2, 5]), list([35, 2, 5])], dtype=object)

>>> pred_1
array([list([8, 32, 3, 25, 2, 3, 2, 5, 8]), list([8, 3, 2, 5, 8])], dtype=object)

【讨论】:

  • 您好,谢谢您的回答,您的labels_1 部分正确,但是对于pred_1,我不想删除-100s(该数组没有),我想要相应的元素到来自labels_1的保留元素的索引。请检查 pred_1 的输出。谢谢
  • 啊,好吧。让我看看……
猜你喜欢
  • 2021-07-29
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 2015-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多