w3resource

NumPy: Count a given word in each row of a array of string values


Write a NumPy program to count a given word in each row of a given array of string values.

Sample Solution:

Python Code:

# Importing necessary library
import numpy as np 

# Creating a NumPy array containing string values
str1 = np.array([['Python','NumPy','Exercises'],
                 ['Python','Pandas','Exercises'],
                 ['Python','Machine learning','Python']])

# Displaying the original array of string values
print("Original array of string values:") 
print(str1)

# Counting occurrences of 'Python' row-wise in the array using np.char.count()
print("\nCount 'Python' row wise in the above array of string values:")
print(np.char.count(str1, 'Python')) 

Sample Output:

Original array of string values:
[['Python' 'NumPy' 'Exercises']
 ['Python' 'Pandas' 'Exercises']
 ['Python' 'Machine learning' 'Python']]

Count 'Python' row wise in the above array of string values:
[[1 0 0]
 [1 0 0]
 [1 0 1]]

Explanation:

In the above code –

str1 = np.array([['Python','NumPy','Exercises'], ['Python','Pandas','Exercises'], ['Python','Machine learning','Python']]): This code creates a NumPy array str1 of shape (3,3)

np.char.count(str1, 'Python'): The np.char.count() function is applied on str1 with the search string 'Python'. It counts the number of occurrences of 'Python' in each string element of str1.

The final output is:

[[1 0 0]

[1 0 0]

[1 0 1]]

This is because the first row contains 'Python' only once, the second row contains 'Python' only once, and the third row contains 'Python' twice.

Python-Numpy Code Editor: