counts of unique values in rows of given 2D array numpy 1

counts of unique values in rows of given 2D array numpy

mat5 = np.array([['a', 'g', 'c'], 
         		 ['a', 'b', 'c'], 
         		 ['f', 'c', 'c']])
val, cnts = np.unique(mat5, return_counts=True)
dict_unique = {k: v for k, v in zip(val, cnts)}
""" result: {'a': 2, 'b': 1, 'c': 4, 'f': 1, 'g': 1} """

Here is what the above code is Doing:
1. np.unique(mat5) returns a tuple of two arrays:
a. The first array contains the unique values in mat5
b. The second array contains the counts of each unique value in mat5
2. The return_counts=True parameter tells np.unique() to return the counts of each unique value in mat5
3. The val and cnts variables are assigned to the two arrays returned by np.unique()
4. The dict_unique variable is assigned to a dictionary that contains the unique values in mat5 as keys and their counts as values

Similar Posts