【问题标题】:python search and find specify numbers location in array 2dpython搜索并查找数组2d中的指定数字位置
【发布时间】:2019-03-30 02:00:19
【问题描述】:

我有数组 np.array 二维数组

[[8, 12, 5, 2], [12,15, 6,10], [15, 8, 12, 5], [12,15,8,6]]

我想创建另一个二维数组 ,(数组中的每个数字,重复的次数,位置)

(2,1,[1,4]), (5,2,[1,3],[3,4]) ,(6,2,[2,3],[4,4]) , (8,3,[1,1],[3,1],[4,3]) (12,4,[1,2],[2,1],[3,3],[4,1]) ,(15,3,[2,2],[3,1],[4,2])
I'd like to generate comparisons between rows and columns.

解释一下(以15号为例)

重复:3

位置:[2,2],[3,1],[4,2]

【问题讨论】:

    标签: python python-3.x python-2.7 numpy


    【解决方案1】:

    这是使用np.unqiuenp.where 的一种方式,注意numpy array 中的索引是从0 开始而不是1

    x,y=np.unique(a.ravel(), return_counts=True)
    l=[]
    for v,c in zip(x,y):
        l.append((v,c,np.column_stack(np.where(a==v)).tolist()))
    
    
    l
    Out[344]: 
    [(2, 1, [[0, 3]]),
     (5, 2, [[0, 2], [2, 3]]),
     (6, 2, [[1, 2], [3, 3]]),
     (8, 3, [[0, 0], [2, 1], [3, 2]]),
     (10, 1, [[1, 3]]),
     (12, 4, [[0, 1], [1, 0], [2, 2], [3, 0]]),
     (15, 3, [[1, 1], [2, 0], [3, 1]])]
    

    【讨论】:

      【解决方案2】:

      使用这篇文章中的代码 Most efficient way to sort an array into bins specified by an index array? 作为模块 stb 我们可以做到

      import numpy as  np
      from stb import sort_to_bins_sparse as sort_to_bins
      from pprint import pprint
      
      X = np.array([[8, 12, 5, 2], [12,15, 6,10], [15, 8, 12, 5], [12,15,8,6]])
      
      unq, inv, cnt = np.unique(X, return_inverse=True, return_counts=True)
      sidx = sort_to_bins(inv, np.arange(X.size))
      # or (slower but avoids dependency on stb module)
      # sidx = np.argsort(inv, kind='stable')
      
      pprint(list(zip(unq, cnt, np.split(np.transpose(np.unravel_index(sidx, X.shape)) + 1, cnt[:-1].cumsum()))))[(2, 1, array([[1, 4]])),
      #  (5, 2, array([[1, 3],
      #        [3, 4]])),
      #  (6, 2, array([[2, 3],
      #        [4, 4]])),
      #  (8, 3, array([[1, 1],
      #        [3, 2],
      #        [4, 3]])),
      #  (10, 1, array([[2, 4]])),
      #  (12, 4, array([[1, 2],
      #        [2, 1],
      #        [3, 3],
      #        [4, 1]])),
      #  (15, 3, array([[2, 2],
      #        [3, 1],
      #        [4, 2]]))]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-09
        • 1970-01-01
        • 2021-08-14
        • 2015-01-31
        • 2020-05-10
        • 2023-03-28
        • 1970-01-01
        相关资源
        最近更新 更多