How to Count the Occurrence of a Certain Item in an Ndarray

How do I count the occurrence of a certain item in an ndarray?

Using numpy.unique:

import numpy
a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
unique, counts = numpy.unique(a, return_counts=True)

>>> dict(zip(unique, counts))
{0: 7, 1: 4, 2: 1, 3: 2, 4: 1}

Non-numpy method using collections.Counter;

import collections, numpy
a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
counter = collections.Counter(a)

>>> counter
Counter({0: 7, 1: 4, 3: 2, 2: 1, 4: 1})

How to count occurrences of string in numpy array?

np.where returns a numpy array, not a pandas series. So you want:

(correct=='INCORRECT').sum()

How to calculate occurrence number of each item in numpy arrays

You can use collections.Counter approach to count occurances and later merge to existing tuples:

[k + (v,) for k, v in Counter(array_element).items()]

Example:

from collections import Counter

array_element = [('T10', 'R1T0'), ('T20', 'R2T0'), ('T31', 'R3T1'), ('T21', 'R2T1'),
('T10', 'R1T0'), ('T20', 'R2T0')]

print([k + (v,) for k, v in Counter(array_element).items()])
# [('T10', 'R1T0', 2) ('T20', 'R2T0', 2) ('T31', 'R3T1', 1) ('T21', 'R2T1', 1)]

How to count occurances of multiple items in numpy?

# Setting your input to an array
array = np.array([1,2,3,1,2,3,1,2,3,1,2,2])

# Find the unique elements and get their counts
unique, counts = np.unique(array, return_counts=True)

# Setting the numbers to get counts for as a set
search = {1, 2}

# Gets the counts for the elements in search
search_counts = [counts[i] for i, x in enumerate(unique) if x in search]

This will output [4, 5]

Count occurrence´s of Element in numpy array (list)

A simple modification of your code to get counts of roll values. If you specifically wanted to make use of Numpy let me know.

Code

from random import randint  # only using randint so only import it
import numpy as np # not needed

class Dice:
def roll(self):
return randint(1, 6)

frequencies = [0]*13 # array to hold results of dice roll
# will use frequencies 2 to 12)

dice = Dice()
remaining_rolls = 10000 # number of remaining rolls
while remaining_rolls > 0:
roll = dice.roll() + dice.roll() # roll sum
frequencies[roll] += 1 # increment array at index roll by 1
remaining_rolls -= 1

print(frequencies)

Output

[0, 0, 272, 583, 829, 1106, 1401, 1617, 1391, 1123, 863, 553, 262]

Using List Comprehension as an alternative to while loop

frequencies = [0]*13 
for roll in [dice.roll() + dice.roll() for _ in range(10000)]:
frequencies[roll] += 1
print(frequencies) # Simpler Output

Explanation

Assignment:

frequencies = [0]*13

Creates an array with 13 elements, with index from 0 to 12 initially filled with zeros.

The sum of each dice roll is a number between 2 and 12 (i.e. 11 values)

To increment a count of a roll we use:

 frequencies[roll] += 1

This is syntactic sugar for:

frequencies[roll] = frequencies[roll] + 1

For instance, if roll = 5 we add 1 to frequencies[5]
This increments the count for the number of times the roll is 5.

Two bins are always zero:

frequencies[0] and frequencies[1]

This is because 2 <= roll <= 12 so we never increment bins 0 and 1.

How do I count the occurrence of a certain item in an ndarray?

Using numpy.unique:

import numpy
a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
unique, counts = numpy.unique(a, return_counts=True)

>>> dict(zip(unique, counts))
{0: 7, 1: 4, 2: 1, 3: 2, 4: 1}

Non-numpy method using collections.Counter;

import collections, numpy
a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
counter = collections.Counter(a)

>>> counter
Counter({0: 7, 1: 4, 3: 2, 2: 1, 4: 1})

Frequency counts for unique values in a NumPy array

Take a look at np.bincount:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html

import numpy as np
x = np.array([1,1,1,2,2,2,5,25,1,1])
y = np.bincount(x)
ii = np.nonzero(y)[0]

And then:

zip(ii,y[ii]) 
# [(1, 5), (2, 3), (5, 1), (25, 1)]

or:

np.vstack((ii,y[ii])).T
# array([[ 1, 5],
[ 2, 3],
[ 5, 1],
[25, 1]])

or however you want to combine the counts and the unique values.

Occurrence of list in ndarray

Whereas its possible to use Counter or opencv histogram function to compute frequency of every single pixel , for specific pixels, its more efficient to use this:

import numpy as np

ar = np.ones([3,3,3]) *255
ar[1,1,:] = [0, 0, 200]

pixels = dict()
pixels['[255, 255, 255]'] = np.sum(np.all(ar == [255,255, 255], axis = 2))
pixels['[0, 0, 200]'] = np.sum(np.all(ar == [0, 0, 200], axis = 2))

result : {'[255, 255, 255]': 8, '[0, 0, 200]': 1}

How do I count the occurrences of a list item?

If you only want a single item's count, use the count method:

>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3


Important: this is very slow if you are counting multiple different items

Each count call goes over the entire list of n elements. Calling count in a loop n times means n * n total checks, which can be catastrophic for performance.

If you want to count multiple items, use Counter, which only does n total checks.



Related Topics



Leave a reply



Submit