NumPy find() function
In this tutorial, we will cover find()
function in the char module of the Numpy Library in Python.
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))
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))
The array is :
['AAAabbbbbxcccccyyysss', 'AAAAAAAaattttds', 'AAaaxcutt', 'AAaaxXDSDdscz']
The find of 'xc' [ 9 -1 4 -1]
The find of 'xc' [ 9 -1 -1 -1]
Summary
In this tutorial, we learned about find()
function of the Numpy Library along with a few code examples. If you want to try a few code examples you can do so in our Python code compiler.