NumPy strings.count()
The numpy.strings.count() function counts the number of non-overlapping occurrences of a substring within string arrays. It allows specifying a search range within the string.
Syntax
</>
Copy
numpy.strings.count(a, sub, start=0, end=None)
Parameters
| Parameter | Type | Description |
|---|---|---|
a | array_like (StringDType, bytes_, or str_ dtype) | Array of strings where the substring will be searched. |
sub | array_like (StringDType, bytes_, or str_ dtype) | The substring to count occurrences of. |
start | array_like (integer dtype), optional | Starting index for substring search (default is 0). |
end | array_like (integer dtype), optional | Ending index for substring search (default is full string length). |
Return Value
Returns an array of integers indicating the count of the specified substring in each string element.
Examples
1. Counting a Substring in an Array of Strings
In this example, we count how many times the letter 'a' appears in an array of fruit names.
</>
Copy
import numpy as np
# Define an array of fruit names
fruits = np.array(['apple', 'banana', 'cherry', 'grape'])
# Count occurrences of 'a' in each string
count_a = np.char.count(fruits, 'a')
# Print results
print("Fruits:", fruits)
print("Occurrences of 'a':", count_a)
Output:
Fruits: ['apple' 'banana' 'cherry' 'grape']
Occurrences of 'a': [0 3 0 1]
