NumPy: Count the lowest index of "P" in a given array, element-wise
NumPy String: Exercise-16 with Solution
Write a NumPy program to count the lowest index of "P" in a given array, element-wise.
Sample Solution:
Python Code:
# Importing necessary library
import numpy as np
# Creating a NumPy array containing strings
x1 = np.array(['Python', 'PHP', 'JS', 'EXAMPLES', 'HTML'], dtype=np.str)
# Displaying the content of the original array
print("\nOriginal Array:")
print(x1)
# Finding the lowest index of the character 'P' in each string of the array x1
print("Count the lowest index of ‘P’:")
r = np.char.find(x1, "P")
print(r)
Sample Input:
(['Python', 'PHP', 'JS', 'EXAMPLES', 'HTML'], dtype=np.str)
Sample Output:
Original Array: ['Python' 'PHP' 'JS' 'EXAMPLES' 'HTML'] count the lowest index of ‘P’: [ 0 0 -1 4 -1]
Explanation:
In the above exercise –
np.array(['Python', 'PHP', 'JS', 'EXAMPLES', 'HTML'], dtype=np.str): This line creates a NumPy array with 5 string values.
np.char.find(x1, "P"): This code searches for the index position of the first occurrence of the character "P" in each string of the numpy array x1. The function returns an array of integers with the index position of "P" in each string, or -1 if the character is not found.
So the resulting r array will be [0, 0, -1, 4, -1], indicating that "P" is found at index 0 in the first two strings ("Python" and "PHP"), not found in the third ("JS"), found at index 4 in the fourth ("EXAMPLES"), and not found in the fifth ("HTML").
Pictorial Presentation:
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a NumPy program to count the number of "P" in a given array, element-wise.
Next: Write a NumPy program to check if each element of a given array is composed of digits only, lower case letters only and upper case letters only.
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://www.w3resource.com/python-exercises/numpy/python-numpy-string-exercise-16.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics