w3resource

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


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

Python-Numpy Code Editor: