NumPy find() function

The find() function finds the substring in a given array of string, between the provided range [start, end] returning the first index from where the substring starts.

This function calls str.find function internally in an element-wise manner.

Syntax of find():

The syntax required to use this method is as follows:

numpy.char.find(a, sub, start, end=None)

The above syntax indicates that find() is a function of the char module and takes the parameters as mentioned above.

Parameters:

let us now take a look at the parameters of this function:

  • a It can either be an input array or an input string.
  • sub This is a required parameter indicating the substring to search from the input string.
  • start, end These parameters are optional, both start and end are used to set the boundary within which the substring is to be searched.

Returned Values:

The find() function will return an output array of integers. If the sub is not found then this function will return -1.

Example 1: Substring found

The code snippet is as follows where we will use find() function:

import numpy as np 

arr = ['AAAabbbbbxcccccyyysss', 'AAAAAAAaattttdsxxxxcccc', 'AAaaxxxxcccutt', 'AAaaxxccxcxXDSDdscz'] 
print ("The array is :\n ", arr) 

print ("\nThe find of 'xc'", np.char.find(arr, 'xc')) 
print ("The find of 'xc'", np.char.find(arr, 'xc', start = 3)) 
print ("The find of 'xc'", np.char.find(arr, 'xc', start = 8)) 

Output:

using numpy find() method example

Example 2: Some substrings not found

import numpy as np 

arr = ['AAAabbbbbxcccccyyysss', 'AAAAAAAaattttds', 'AAaaxcutt', 'AAaaxXDSDdscz'] 
print ("The array is :\n ", arr) 

print ("\nThe find of 'xc'", np.char.find(arr, 'xc')) 
print ("The find of 'xc'", np.char.find(arr, 'xc', start = 8)) 

Output:

The array is : 
['AAAabbbbbxcccccyyysss', 'AAAAAAAaattttds', 'AAaaxcutt', 'AAaaxXDSDdscz'] 

The find of 'xc' [ 9 -1 4 -1] 
The find of 'xc' [ 9 -1 -1 -1]
Follow Us On