How do you Count The Number Of Times Each Value Appears In An Array Of
Integers?
[0, 5, 4, 0, 4, 4, 3, 0, 0, 5, 2, 1, 1, 9]
Answer should be array([4, 2, 1, 1, 3, 2, 0, 0, 0, 1]) which means 0 comes 4 times,
1 comes 2 times, 2 comes 1 time, 3 comes 1 time and so on.python
Apr 21, 2020 1,674 views

Hey, @Sourav,

We can solve this with the collection module, which refers to count frequencies of all elements in the array link.

```import collections #Function to count frequency of each element it returns a dictionary data structure whose keys are array elements and values are their corresponding frequencies {0: 4,  1: 2,  2: 1,  3: 1]

def CountFrequency(arr):

return collections.Counter(arr)  ```
```if __name__ == "__main__": #Driver Function

arr = [0, 5, 4, 0, 4, 4, 3, 0, 0, 5, 2, 1, 1, 9]```

freq = CountFrequency(arr)

```for key, value in freq.iteritems():

print key, " -> ", value```

Output:

0-> 4

1->2

2->1

3->1

Hope this will help you.

• 65,910 points
Thanks Gitika,

It Works.

+1 vote

How to count the number of elements with the values in a vector?

Use dplyr function group_by(). > n = as.data.frame(num) > ...READ MORE

+1 vote

Custom Function to replace missing values in a vector with the mean of values

Try this. lapply(a,function(x){ifelse(is.na(x),mean(a,na.rm = TRUE ...READ MORE

What is the difference between [] and [[]] notations to access the elements of a list or dataframe in R?

R provides 3 basic indexing operators. Refer ...READ MORE

R function for finding the index of an element in a vector?

The function match works on vectors : x <- sample(1:10) x # ...READ MORE

How do I obtain the index list in a NumPy Array of all the NaN values present using Python?

Hi, it is pretty simple, to be ...READ MORE

How to create Pandas series from numpy array?

Hi. Refer to the below command: import pandas ...READ MORE

Pandas series with custom index

You can do it by specifying index. ...READ MORE

+1 vote