Signup/Sign In

NumPy count() function

In this tutorial, we will cover count() function available in the char module of the Numpy library.

The count() function is used to return an array with the count values of non-overlapping occurrences(unique) of a given substring in the range [start, end].

This function calls str.count internally, for every element of the given ndrray.

Syntax of count():

The syntax required to use this method is as follows:

numpy.char.count(a, sub, start, end=None)

Let's cover the parameters of the count() function:

Parameters:

let us now take a look at the parameters of this function:

  • a
    It can either be an input array or an input string.

  • sub
    This is a required parameter indicating the substring to search from the input string or the input array.

  • start, end
    These parameters are optional, both start and end are used to set the boundary within which the substring is to be searched.

Returned Values:

The count() function will return an integer array with the number of non-overlapping occurrences of the substring.

Basic Example of count() function:

The code snippet is as follows where we will use count() function:

import numpy as np

str1 = np.array(['ooooaaaaqqqk','ccccvvvvvaaaao','ggghhhjjjsskkka'])
print("The original string is:\n",str1)
print("\nThe count of 'a' in str1")

y = np.char.count(str1,'a')
print(y)
print("\nThe count of 'k' in st1:")

z = np.char.count(str1,'k')
print(z)
print("\nThe count of 'o' in st1:")

x = np.char.count(str1,'o')
print(x)

using count() function of Numpy

Summary

This tutorial covers the count() function of the Numpy library with code examples.



About the author:
Aspiring Software developer working as a content writer. I like computer related subjects like Computer Networks, Operating system, CAO, Database, and I am also learning Python.