Home > Blockchain >  Numpy: Group of ids after unique
Numpy: Group of ids after unique

Time:12-01

i'm looking for a solution for group data after the use of the unique numpy function. I think an example is better :

>>> t
[[0, 3, 4], [1, 2, 8], [1, 2, 8]] #array of multiples values
>>> ids = ['A', 'B', 'C'] #Ids associated with previous values
>>> np.unique(t, axis=0)
array([[0, 3, 4],
       [1, 2, 8]]) #Result of unique (so 2 rows ofc)
>>> array([['A'],
           ['B', 'C']]) #What i want to got (and generated with numpy ideally)

Thank you very much for your help.

CodePudding user response:

Maybe you can create a dictionary where keys are tuples from elements of t and values are letters from ids

d = {}
for i in range(len(ids)):
    d.setdefault(tuple(t[i]), []).append(ids[i])
d
# {(0, 3, 4): ['A'], (1, 2, 8): ['B', 'C']}

CodePudding user response:

A friend found a good way to do that. (Works only if the data is sorted)

import numpy as np

t = np.array([[0, 3, 4], [1, 2, 8], [1, 2, 8]])
ids = np.array(['A', 'B', 'C'])
print(t)
res = np.split(ids, np.unique(t, return_index=True, axis=0)[1][1:])
print(res) # [array(['A'], dtype='<U1'), array(['B', 'C'], dtype='<U1')]
  • Related