【问题标题】:how do you find and save duplicated rows in a numpy array?您如何在 numpy 数组中查找和保存重复的行?
【发布时间】:2018-06-14 10:22:31
【问题描述】:

我有一个数组,例如

Array = [[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5],[1,1,1],[2,2,2]]

我想要一些可以输出以下内容的东西:

Repeated = [[1,1,1],[2,2,2]]

保留重复行数也可以,例如

Repeated = [[1,1,1],[1,1,1],[2,2,2],[2,2,2]]

我认为解决方案可能包括 numpy.unique,但我无法让它工作,是否有本机 python / numpy 函数?

【问题讨论】:

  • 但 unique 用于获取 unique 数字,而不是重复的数字。这总是整数列表吗?或者对象可以是任意对象吗?
  • 发布的解决方案是否对您有用?

标签: python numpy rows


【解决方案1】:

使用np.unique 的新axis 功能以及return_counts=True,它为我们提供了唯一的行和每行的相应计数,我们可以用counts > 1 屏蔽掉行,从而获得我们想要的输出,就像这样-

In [688]: a = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5],[1,1,1],[2,2,2]])

In [689]: unq, count = np.unique(a, axis=0, return_counts=True)

In [690]: unq[count>1]
Out[690]: 
array([[1, 1, 1],
       [2, 2, 2]])

【讨论】:

  • 是否可以获取重复行的索引?例如,[0, 5][1, 2]
【解决方案2】:

如果需要获取重复行的索引

import numpy as np

a = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5],[1,1,1],[2,2,2]])
unq, count = np.unique(a, axis=0, return_counts=True)
repeated_groups = unq[count > 1]

for repeated_group in repeated_groups:
    repeated_idx = np.argwhere(np.all(a == repeated_group, axis=1))
    print(repeated_idx.ravel())

# [0 5]
# [1 6]

【讨论】:

  • 这对我来说效果很好,正是我想要的。
【解决方案3】:

如果您不一定需要保留订单,则可以使用 Repeated = list(set(map(tuple, Array))) 之类的东西。这样做的好处是你不需要像 numpy 这样的额外依赖。根据您接下来要做的事情,您可能会摆脱 Repeated = set(map(tuple, Array)) 并避免类型转换(如果您愿意)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 2021-02-26
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    相关资源
    最近更新 更多