NumPy: Count a given word in each row of a array of string values
NumPy String: Exercise-21 with Solution
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:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a NumPy program to replace a specific character with another in a given array of string values.
Next: Write a NumPy program to split a given text into lines and split the single line into array values.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/numpy/python-numpy-string-exercise-21.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics