Search code examples
pythonnumpyunique

Get amount of unique elements in numpy


I have an array
arr = np.array([[1,1,2], [1,2,3]]).
I want to get amount of unique element for each row and count mean
I can do this np.array([len(np.unique(row)) for row in arr]).mean().
But seems, that it's a slow way. Is there another faster approach?


Solution

  • You can use the following:

    import numpy as np
    
    arr = np.array([[1, 1, 2], [1, 2, 3]])
    
    
    mean = np.apply_along_axis(lambda row: len(set(row)), axis=1, arr=arr).mean()
    
    >> mean = 2.5