w3resource

NumPy: Count the lowest index of "P" in a given array, element-wise


16. Lowest Index of "P" in Strings

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:

NumPy String: Count the lowest index of

For more Practice: Solve these Related Problems:

  • Create a function that finds the first occurrence index of "P" in each string of an array using np.char.find.
  • Implement a solution that returns -1 for strings where "P" does not occur and validates the output using vectorized operations.
  • Test the function on an array with mixed-case letters to ensure proper index retrieval for uppercase "P."
  • Combine the index finding with a conditional replacement, e.g., replacing the first "P" with another character if found.

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.



Follow us on Facebook and Twitter for latest update.