Return an array with the number of nonoverlapping occurrences of substring in Python

PythonNumpyServer Side ProgrammingProgramming

To return an array with the number of non-overlapping occurrences of substring, use the numpy.char.count() method in Python Numpy. The first parameter is the sub i.e. the substring to search for. The numpy.char module provides a set of vectorized string operations for arrays of type numpy.str_

Steps

At first, import the required library −

import numpy as np

Create a One-Dimensional array of strings −

arr = np.array(['kATIE', 'JOHN', 'KAte', 'AmY', 'BRADley'])

Displaying our array −

print("Array...
",arr)

Get the datatype −

print("
Array datatype...
",arr.dtype)

Get the dimensions of the Array −

print("
Array Dimensions...
",arr.ndim)

Get the shape of the Array −

print("
Our Array Shape...
",arr.shape)

Get the number of elements of the Array −

print("
Number of elements in the Array...
",arr.size)

To return an array with the number of non-overlapping occurrences of substring, use the numpy.char.count() method in Python Nump. The first parameter is the sub i.e. the substring to search for −

print("
Result (count)...
",np.char.count(arr, 'A'))

Example

import numpy as np

# Create a One-Dimensional array of strings
arr = np.array(['kATIE', 'JOHN', 'KAte', 'AmY', 'BRADley'])

# Displaying our array
print("Array...
",arr)

# Get the datatype
print("
Array datatype...
",arr.dtype)

# Get the dimensions of the Array
print("
Array Dimensions...
",arr.ndim)

# Get the shape of the Array
print("
Our Array Shape...
",arr.shape)

# Get the number of elements of the Array
print("
Number of elements in the Array...
",arr.size)

# To return an array with the number of non-overlapping occurrences of substring, use the numpy.char.count() method in Python Numpy
# The first parameter is the sub i.e. the substring to search for
print("
Result (count)...
",np.char.count(arr, 'A'))

Output

Array...
['kATIE' 'JOHN' 'KAte' 'AmY' 'BRADley']

Array datatype...
<U7

Array Dimensions...
1

Our Array Shape...
(5,)

Number of elements in the Array...
5

Result (count)...
[1 0 1 1 1]
raja
Updated on 28-Feb-2022 05:36:55

Advertisements