【问题标题】:Extract unique rows from a matrix in numpy with the frequency of each row that was created使用创建的每一行的频率从 numpy 中的矩阵中提取唯一行
【发布时间】:2013-06-16 20:26:03
【问题描述】:

关于以下问题的后续问题:

How can I use the unique(a, 'rows') from MATLAB in Python?

那里的答案解释了如何获取唯一行。然而,matlab 还返回创建的每一行的频率。有什么优雅的方法可以用 python 制作它?

谢谢!

【问题讨论】:

    标签: python matrix numpy scipy unique


    【解决方案1】:

    您可以使用花哨的索引和评估以下条件来计算每个唯一行的数量:

    from numpy import unique, array, all
    def myunique(input):
        u = array([array(x) for x in set(tuple(x) for x in input)])
        return u, array([len(input[all(input==x, axis=1)]) for x in u],dtype=int)
    

    示例:

    a = array([list('1234'),
               list('1234'),
               list('1222'),
               list('1222'),
               list('1234')],dtype=str)
    
    print myunique(a)
    #(array([['1', '2', '2', '2'],
    #        ['1', '2', '3', '4']],
    #       dtype='|S1'), array([2, 3]))
    

    【讨论】:

    • 只是想我会提到你的 myunique(x) 函数明确引用了... :)
    【解决方案2】:

    numpy_indexed 包(免责声明:我是它的作者)有一个功能可以有效地做到这一点:

    import numpy_indexed as npi
    m = np.random.randint(0, 2, (20, 3))
    unique, count = npi.count(m)
    

    【讨论】:

      【解决方案3】:

      我曾经遇到过这个问题。 我做了以下事情:与其说是一个完美的解决方案,不如说是一个优雅的 hack。

      首先将您的二维数组转换为一维数组或可散列列表,然后就很容易了。 转换为一维浮点数组的一种方法是使用 D 维随机向量进行点积。 例如:

      a = np.array([[1.32,1,4],[2,3,3.5],[1.32,1,4],[4,5,6.2]])
      
      b = np.random.randint(1,10**20,3)
      
      c = np.dot(a,b)
      vals, idx = np.unique(c,True)
      

      【讨论】:

        猜你喜欢
        • 2017-10-10
        • 2017-05-09
        • 1970-01-01
        • 1970-01-01
        • 2015-06-14
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多