What is the numpy.char.count() function in Python?

Overview

The numpy.char.count() function in Python returns an output array with the number of non-overlapping occurrences of a substring in a given range [start, end] from an input array a.

Syntax

char. count(a, sub, start=0, end=None)
Syntax for the char.count() function

Parameter value

The char.count() function takes the following parameter values:

  • a: This is the input array.
  • sub: This is the substring to search for.
  • start, end: This is the slice notation specifying the range, in each element of the given array, where the counting is done.

Return value

The char.count() function returns an array of integers with the same shape as the input array.

Example

import numpy as np
# Creating the input array
a = np.array(['bBbABAbB', 'bB', 'bCBcAcb'])
# Creating the substring to search for
sub = "A"
# Implmenting the char.count() function
myarray = np.char.count(a, sub, start=1, end=5)
# Printing the input and output arrays
print(a)
print(myarray)

Explanation

  • Line 1: We import the numpy module.
  • Line 3: We create the input array a using the array() function.
  • Line 6: We create a substring variable sub to search for.
  • Line 9: We implement the char.count() function on the input array, and search for the number of occurrences of a in the array elements. The result is assigned to a variable myarray.
  • Line 12: We print the input array a.
  • Line 13: We print the output array myarray.

Free Resources