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 arraya = np.array(['bBbABAbB', 'bB', 'bCBcAcb'])# Creating the substring to search forsub = "A"# Implmenting the char.count() functionmyarray = np.char.count(a, sub, start=1, end=5)# Printing the input and output arraysprint(a)print(myarray)
Explanation
- Line 1: We import the
numpymodule. - Line 3: We create the input array
ausing thearray()function. - Line 6: We create a substring variable
subto search for. - Line 9: We implement the
char.count()function on the input array, and search for the number of occurrences ofain the array elements. The result is assigned to a variablemyarray. - Line 12: We print the input array
a. - Line 13: We print the output array
myarray.