# Counting values in an array - Python
Data Science for Political and Social Phenomena
Author: Guillaume Redoulès

# Counting values in an array

## Using lists

If you want to count the number of occurences of an element in a list you can use the .count() function of the list object

    arr = [1,2,3,3,4,5,3,6,7,7]
    print(f'Array : {arr}\n')

    print(f'The number 3 appears {arr.count(3)} times in the list')
    print(f'The number 7 appears {arr.count(7)} times in the list')
    print(f'The number 4 appears {arr.count(4)} times in the list')

    Array : [1, 2, 3, 3, 4, 5, 3, 6, 7, 7]

    The number 3 appears 3 times in the list
    The number 7 appears 2 times in the list
    The number 4 appears 1 times in the list

## Using collections

you can get a dictonnary of the number of occurences of each elements in a list thanks to the collections object like this

    import collections

    collections.Counter(arr)

    Counter({1: 1, 2: 1, 3: 3, 4: 1, 5: 1, 6: 1, 7: 2})

## Using numpy

You can have a simular result with numpy by hacking the unique function

    import numpy as np
    arr = np.array(arr)
    unique, counts = np.unique(arr, return_counts=True)
    dict(zip(unique, counts))

    {1: 1, 2: 1, 3: 3, 4: 1, 5: 1, 6: 1, 7: 2}

### Find an error or bug? Have a suggestion?

Everything on this site is avaliable on GitHub. Head on over and submit an issue. You can also message me directly by email.