count() function - NumPy String Operation
The numpy.char.count() function is used to count the number of non-overlapping occurrences of a substring within each element of a string array. It can also take optional start and end positions to limit the search to a substring range.
For Example: This example counts how many times "o" appears in each word.
import numpy as np
arr = np.array(['book', 'moon', 'loop'])
res = np.char.count(arr, sub='o')
print(res)
Output
[2 2 2]
Explanation: Each word contains two "o" characters, so the result is [2 2 2].
Syntax
numpy.char.count(arr, sub, start=0, end=None)
Parameters:
- arr: array_like -> Input array of strings.
- sub: str -> Substring to search for.
- start: int, optional -> Starting position (default 0).
- end: int, optional -> Ending position (default None, till end of string).
Return Value: ndarray -> Array of integers showing the count of substring occurrences.
Examples
Example 1: This example counts the occurrences of "an" in each string.
import numpy as np
arr = np.array(['Sayantan', 'Sayan', 'Sayansubhra'])
res = np.char.count(arr, sub='an')
print(res)
Output
[2 1 1]
Explanation:
- "Sayantan" -> contains "an" twice
- "Sayan" -> contains "an" once
- "Sayansubhra" -> contains "an" once
Example 2: This example counts how many times "e" appears in city names.
import numpy as np
arr = np.array(['Berlin', 'Venice', 'New Delhi'])
res = np.char.count(arr, sub='e')
print(res)
Output
[1 2 2]
Explanation:
- "Berlin" -> one "e"
- "Venice" -> two "e"
- "New Delhi" -> two "e"
Example 3: This example counts digits inside numeric strings.
import numpy as np
arr = np.array(['10101', '12345', '111'])
res = np.char.count(arr, sub='1')
print(res)
Output
[3 1 3]
Explanation: Counts of "1" are 3, 1 and 3 for the respective strings.