如何有效地从两个列表中删除一个列表中具有特定值的所有索引?

2024-04-25 19:40:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个numpy数组,试图从中删除第二个数组中值为-1的所有索引。你知道吗

示例:

goldLabels = np.array([12, 2, 0, 0, 0, 1, 5])
predictions = np.array([12, 3, 0, 2, -1, -1, -1])

预期结果:

>>> print(goldLabels)
[12, 2, 0, 0]  
>>> print(predictions) 
[12, 3, 0, 2]

这是我目前的代码:

idcs = []
for idx, label in enumerate(goldLabels):
    if label == -1: 
        idcs.append(idx)
goldLabels = np.delete(goldLabels, idcs)
predictions = np.delete(predictions, idcs)

有什么办法能更有效地做到这一点吗?你知道吗


Tags: 代码innumpy示例fornp数组delete
1条回答
网友
1楼 · 发布于 2024-04-25 19:40:08

您可以使用numpy的功能,使用掩码直接提取这些数字:

goldLabels = np.array([12, 2, 0, 0, 0, 1, 5])
predictions = np.array([12, 3, 0, 2, -1, -1, -1])

mask = predictions!=-1 
predictions = predictions[mask]
goldLabels = goldLabels[mask]

print(goldLabels)
print(predictions) 

输出:

[12  2  0  0]
[12  3  0  2]

相关问题 更多 >