【问题标题】:Removing rows in a 2D array that have the same value删除二维数组中具有相同值的行
【发布时间】:2015-02-25 22:42:17
【问题描述】:

我正在寻找一种以先到先得的方式删除二维数组中存在的重复值的快速方法。如果它们相同,我知道一种删除行的方法,但如果只有一个值存在,则不会。

a = array([[0, 1],
           [3, 4],
           [3, 5],
           [2, 5],
           [1, 2]])

由于 3 存在于 a[1] 和 a[2] 中,我想删除任何未来出现的值。与 a[3] 和 a[4] 中的 2 类似,因此输出将是:

a = array([[0, 1],
           [3, 4],
           [2, 5]])

可以看出,与值 5 有重叠。欢迎提出任何建议。

【问题讨论】:

  • 您愿意接受纯 Python 解决方案吗?
  • 是的,任何解决方案都是可行的。谢天谢地,我最多处理 20/30 行。优化应该不是什么大问题。

标签: python arrays numpy


【解决方案1】:

纯 Python 方法是使用带有列表理解的集合:

>>> seen = set()
>>> np.array([x for x in a if seen.isdisjoint(x) and not seen.update(x)])
array([[0, 1],
       [3, 4],
       [2, 5]])

单行只是滥用set.update返回None这一事实,所以当seen.isdisjoint(x)True时,我们可以使用not seen.update(x)更新seen集合。

我们也可以把上面的代码写成:

seen = set()
out = []
for item in a:
    # if none of items in current sub-array are present in seen set
    # then add current sub-array to our list. Plus update the seen
    # set with the items from current sub-array
    if seen.isdisjoint(item):
        out.append(item)
        seen.update(item)
...         
>>> out
[array([0, 1]), array([3, 4]), array([2, 5])]
>>> np.array(out)
array([[0, 1],
       [3, 4],
       [2, 5]])

【讨论】:

  • 作为一个 Python 新手,我喜欢看到关于集合操作和 NumPy 数组如何协同工作的句子。也许我不太了解场景,但这对我来说似乎是巫术
  • 这个方法很好用,谢谢。它也非常快,这有帮助。我自己是python的新手。我的第一直觉是一组循环和 if 语句。但这很优雅。
  • @ArcAngel 我添加了一个更简单的单线版本,并在 cmets 中进行了解释。
猜你喜欢
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 2023-03-31
相关资源
最近更新 更多