NumPy: Count a given word in each row of a array of string values
21. Count Word Occurrences Row-wise
Write a NumPy program to count a given word in each row of a given array of string values.
Sample Solution:
Python Code:
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.
For more Practice: Solve these Related Problems:
- Create a function that counts the occurrences of a specific word in each row of a 2D array of strings using np.char.count.
- Implement a solution that returns a 2D array where each element represents the count of a target word in the corresponding row.
- Test the function on an array where rows contain multiple words and verify counts against expected frequencies.
- Combine the word count with a filter that extracts only those rows where the count exceeds a given threshold.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics