【问题标题】:python most common pair of indices in 3 x n arraypython 3 x n 数组中最常见的索引对
【发布时间】:2017-12-14 09:59:34
【问题描述】:

我有一个形状为 (3, 600219) 的 numpy 数组,它是一个索引列表。

array([[   0,    0,    0, ..., 2879, 2879, 2879],
       [  40,   40,   40, ...,  162,  165,  168],
       [ 249,  250,  251, ...,  195,  196,  198]])

第一行是时间索引,第二行和第三行是坐标索引。我试图找出最常出现的坐标对,不考虑时间。

例如是 (49,249) 还是 (40,250)...等等?

【问题讨论】:

  • 您可以在 O(N^2) 中执行此操作,方法是在每根绳子上进行操作并询问它在数组中出现的次数。或者您可以对数组进行排序,而不是搜索绳索,在 O(N*log(N)) 中完成这项工作,但它有点复杂。
  • 你知道最大坐标尺寸吗?

标签: python arrays sorting numpy weather


【解决方案1】:

我只是使用了你的一小部分数据,但我想你会明白的:

import numpy as np

array = np.array([[   0,    0,    0, 2879, 2879, 2879],
       [  40,   40,   40, 162,  165,  168],
       [ 249,  250,  251, 195,  196,  198]])

# Zip together only the second and third rows
only_coords = zip(array[1,:], array[2,:])

from collections import Counter

Counter(only_coords).most_common()

生产:

Out[11]: 
[((40, 249), 1),
 ((165, 196), 1),
 ((162, 195), 1),
 ((168, 198), 1),
 ((40, 251), 1),
 ((40, 250), 1)]

【讨论】:

  • 在压缩行上调用 list() 似乎非常多余,因为在 python2 zip 中已经输出了一个列表,而在 python3 zip 返回一个可与 Counter 一起正常工作的迭代器,并且内存更多在大型数据集的情况下特别友好
【解决方案2】:

这是一种矢量化方法 -

IDs = a[1].max()+1 + a[2]
unq, idx, count = np.unique(IDs, return_index=1,return_counts=1)
out = a[1:,idx[count.argmax()]]

如果可能存在负坐标,请使用a[1].max()-a[1].min()+1 + a[2] 计算IDs

示例运行 -

In [44]: a
Out[44]: 
array([[8, 3, 6, 6, 8, 5, 1, 6, 6, 5],
       [5, 2, 1, 1, 5, 1, 5, 1, 1, 4],
       [8, 2, 3, 3, 8, 1, 7, 3, 3, 3]])

In [47]: IDs = a[1].max()+1 + a[2]

In [48]: unq, idx, count = np.unique(IDs, return_index=1,return_counts=1)

In [49]: a[1:,idx[count.argmax()]]
Out[49]: array([1, 3])

【讨论】:

    【解决方案3】:

    这可能看起来有点抽象,但您可以尝试将每个坐标保存为一个数字,例如[2,1] = 2.1。并将您的数据放入这些坐标的列表中。例如,第 2 行 [1,1,2] 和第 3 行 [2,2,1] 将是 [1.2, 1.2, 2.1] 您可以使用以下代码:

    from collections import Counter
    list1=[1.2,1.2,2.1]
    data = Counter(list1)
    print (data.most_common(1))  # Returns the highest occurring item
    

    它会打印最常见的数字,以及它出现的次数,然后如果您需要在代码中使用它,您可以简单地将数字转换回坐标。

    【讨论】:

      【解决方案4】:

      这是一个计算示例代码:

      import numpy as np
      import collections
      
      a = np.array([[0, 1, 2, 3], [10, 10, 30 ,40], [25, 25, 10, 50]])
      # You don't care about time
      b = np.transpose(a[1:])
      
      # convert list items to tuples
      c = map(lambda v:tuple(v), b)
      collections.Counter(c)
      

      输出:

      Counter({(10, 25): 2, (30, 10): 1, (40, 50): 1})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多