I have a numpy array (in Python 3) having say 4 unique values plus 0s in it (the number of unique values is dynamic and can change). Currently, the mapping between unique values and their indices is being done as follows:
For example, the given np array (3, 3, 3) has values-
array([[[ 0. , 0. , 0. ],
[ 0. , 0. , 0. ],
[ 0.13891649, 0. , -0.14964542]],
[[ 0.14316492, 0.16461118, 0.10582511],
[ 0.09232809, 0. , 0. ],
[ 0. , 0. , 0. ]],
[[ 0. , 0. , 0. ],
[ 0. , -0.13443717, 0. ],
[ 0. , -0.15175688, 0. ]]], dtype=float32)
This array has 4 unique value (without 0)-
array([-0.1284381 , -0.1008032 , 0. , 0.02159981, 0.08796175],
dtype=float32)
Current mapping for unique values and their indices is done by:
wts, count = np.unique(x, return_counts=True)
unique_counts_cl1 = dict(zip(wts, count))
unique_counts_cl1
# {-0.1284381: 1, -0.1008032: 2, 0.0: 19, 0.02159981: 3, 0.08796175: 2}
cl1_wts_mapping = {}
wt_indx = 1
for wt in unique_counts_cl1.keys():
# print(wt, list(unique_counts.keys())[wt_indx - 1])
cl1_wts_mapping['wt' + str(wt_indx)] = np.where(x == list(unique_counts_cl1.keys())[wt_indx - 1])
wt_indx += 1
# This creates the mapping-
cl1_wts_mapping
'''
{'wt1': (array([0]), array([2]), array([2])),
'wt2': (array([2, 2]), array([1, 2]), array([1, 1])),
'wt3': (array([0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]),
array([0, 0, 0, 1, 1, 1, 2, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 2, 2]),
array([0, 1, 2, 0, 1, 2, 1, 1, 2, 0, 1, 2, 0, 1, 2, 0, 2, 0, 2])),
'wt4': (array([1, 1, 1]), array([0, 0, 1]), array([0, 2, 0])),
'wt5': (array([0, 1]), array([2, 0]), array([0, 1]))}
'''
# To access 2nd unique weight-
cl1_wts_mapping['wt2']
# (array([2, 2]), array([1, 2]), array([1, 1]))
Is there a better/efficient way to achieve the mapping?
Thanks!