【问题标题】:Calculate the duplicate in multidimensional numpy array计算多维numpy数组中的重复项
【发布时间】:2019-06-16 12:30:07
【问题描述】:

我正在使用 python-3.x,我想计算 numpy 数组中的重复数....例如:

import numpy as np
my_array = np.array([[2, 3, 5],
                     [2, 3, 5], # duplicate of row 0 (this will be count as 1)
                     [2, 3, 5], # duplicate of row 0 (this will be count as 2)
                     [1, 0, 9], 
                     [3, 6, 6], 
                     [3, 6, 6], # duplicate of row 0 (this will be count as 3)
                     [1, 0, 9]])

我想从输出中得到的是这个数组中重复的数量:

the number of the duplicate is 3

大多数方法都返回值,例如 collections.Counter 或 return_counts,如果我正确使用它们,它们不会返回我想要的。

任何建议将不胜感激

【问题讨论】:

    标签: python-3.x numpy multidimensional-array duplicates


    【解决方案1】:

    您可以通过取数组长度-数组唯一成员的长度来获取数组的重复计数:

    the_number_of the duplicate = len(my_array) - len(np.unique(my_array, axis=0))
    

    您示例的结果是 4([1,0,9] 也是重复的)。

    【讨论】:

    • 非常感谢您的建议 :)
    【解决方案2】:

    这与@Anh Ngoc 的回答略有不同。 (对于旧版本的 numpy,np.unique 不支持 axis

    number_of_duplicates = len(my_array) - len(set(map(tuple, my_array)))
    

    【讨论】:

    • 非常感谢,没想到会像你的回答这么简单:)
    猜你喜欢
    • 2021-08-29
    • 2012-11-01
    • 2011-07-08
    • 2021-08-29
    • 2019-06-03
    • 1970-01-01
    • 2019-05-17
    • 2019-02-21
    • 2012-01-07
    相关资源
    最近更新 更多