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

To return an array with the number of non-overlapping occurrences of substring, use the numpy.char.count() method in Python NumPy. The numpy.char module provides vectorized string operations for arrays of type numpy.str_ or numpy.bytes_.

Syntax

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

Parameters

a ? Input array of strings
sub ? Substring to search for
start ? Optional start position (default: 0)
end ? Optional end position (default: None)

Example 1: Basic Character Count

Count occurrences of a specific character in string array ?

import numpy as np

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

# Display the array
print("Array:")
print(arr)

# Count occurrences of 'A'
result = np.char.count(arr, 'A')
print("\nCount of 'A' in each string:")
print(result)
Array:
['kATIE' 'JOHN' 'KAte' 'AmY' 'BRADley']

Count of 'A' in each string:
[1 0 1 1 1]

Example 2: Substring Count

Count occurrences of longer substrings ?

import numpy as np

# Array with repeated substrings
words = np.array(['banana', 'ababa', 'hello', 'ananana'])

# Count 'an' occurrences (non-overlapping)
an_count = np.char.count(words, 'an')
print("Count of 'an':")
print(an_count)

# Count 'ana' occurrences (non-overlapping)
ana_count = np.char.count(words, 'ana')
print("\nCount of 'ana':")
print(ana_count)
Count of 'an':
[2 0 0 3]

Count of 'ana':
[1 0 0 2]

Example 3: Case-Sensitive Counting

Demonstrate case sensitivity in substring counting ?

import numpy as np

# Mixed case array
text_array = np.array(['Python', 'PYTHON', 'python', 'PyThOn'])

# Count lowercase 'py'
lower_py = np.char.count(text_array, 'py')
print("Count of 'py':")
print(lower_py)

# Count uppercase 'PY'
upper_py = np.char.count(text_array, 'PY')
print("\nCount of 'PY':")
print(upper_py)
Count of 'py':
[0 0 1 0]

Count of 'PY':
[0 1 0 0]

Key Points

− The function counts non-overlapping occurrences only
− Counting is case-sensitive
− Returns an array with the same shape as input
− Works with both single characters and multi-character substrings

Conclusion

The numpy.char.count() method efficiently counts non-overlapping substring occurrences in string arrays. It's case-sensitive and returns an integer array with counts for each input string.

Updated on: 2026-03-26T19:27:22+05:30

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements