Search code examples
pythonarraysnumpyfrequency

Counting occurrences of elements of one array given another array


I want to find the frequency of the values of one array (arr1) given another array (arr2). They are both one-dimensional, and arr2 is sorted and has no repeating elements.

Example:

arr1 = np.array([1, 0, 3, 0, 3, 0, 3, 0, 8, 0, 1, 8, 0])
arr2 = np.array([0, 1, 2, 8])

The output should be: freq= np.array([6, 2, 0, 2)]

What I was trying was this:

arr2, freq = np.unique(arr1, return_counts=True)

But this method doesn't output values that have frequency of 0.


Solution

  • One way to do it can be like below:

    import numpy as np
    
    arr1 = np.array([1, 0, 3, 0, 3, 0, 3, 0, 8, 0, 1, 8, 0])
    arr2 = np.array([0, 1, 2, 8])
    
    arr3, freq  = np.unique(arr1, return_counts=True)
    dict_ = dict(zip(arr3, freq))
    
    freq = np.array([dict_[i] if i in dict_ else 0 for i in arr2])
    freq
    

    Output:

    [6, 2, 0, 2]
    

    Alternative One-liner Solution

    import numpy as np
    
    arr1 = np.array([1, 0, 3, 0, 3, 0, 3, 0, 8, 0, 1, 8, 0])
    arr2 = np.array([0, 1, 2, 8])
    
    freq = np.array([np.count_nonzero(arr1 == i) for i in arr2])