-2

i have array np.array two dimensional array

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

i want to create another 2d array , (each number in array,how many repeated,locations)

(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.

to explain (let take no. 15 as example)

repeated:3

locations:[2,2],[3,1],[4,2]

cs95
  • 379,657
  • 97
  • 704
  • 746
S. Waleed
  • 39
  • 5

2 Answers2

1

Here is one way using np.unqiue and np.where, notice the index in numpy array is start from 0 not 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]])]
BENY
  • 317,841
  • 20
  • 164
  • 234
1

Using code from this post Most efficient way to sort an array into bins specified by an index array? as module stb we can do

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]]))]
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99