Return Boolean Array for String Suffix in Python



To return a boolean array which is True where the string element in array ends with suffix, use the numpy.char.endswith() method in Python Numpy. The first parameter is the input array. The second parameter is the suffix. The numpy.char module provides a set of vectorized string operations for arrays of type numpy.str_

Steps

At first, import the required libraries −

import numpy as np

Create a One-Dimensional array of strings −

arr = np.array(['KATIE', 'JOHN', 'KATE', 'AmY', 'BRADley'])

Displaying our array −

print("Array...\n",arr)

Get the datatype −

print("\nArray datatype...\n",arr.dtype)

Get the dimensions of the Array −

print("\nArray Dimensions...\n",arr.ndim)

Get the shape of the Array −

print("\nOur Array Shape...\n",arr.shape)

Get the number of elements of the Array −

print("\nNumber of elements in the Array...\n",arr.size)

To return a boolean array which is True where the string element in array ends with suffix, use the numpy.char.endswith() method −

print("\nResult (endswith)...\n",np.char.endswith(arr, 'E'))

Example

Open Compiler
import numpy as np # Create a One-Dimensional array of strings arr = np.array(['KATIE', 'JOHN', 'KATE', 'AmY', 'BRADley']) # Displaying our array print("Array...\n",arr) # Get the datatype print("\nArray datatype...\n",arr.dtype) # Get the dimensions of the Array print("\nArray Dimensions...\n",arr.ndim) # Get the shape of the Array print("\nOur Array Shape...\n",arr.shape) # Get the number of elements of the Array print("\nNumber of elements in the Array...\n",arr.size) # To return a boolean array which is True where the string element in array ends with suffix, use the numpy.char.endswith() method in Python Numpy # The first parameter is the input array # The second parameter is the suffix print("\nResult (endswith)...\n",np.char.endswith(arr, 'E'))

Output

Array...
['KATIE' 'JOHN' 'KATE' 'AmY' 'BRADley']

Array datatype...
<U7

Array Dimensions...
1

Our Array Shape...
(5,)

Number of elements in the Array...
5

Result (endswith)...
[ True False True False False]
Updated on: 2022-03-01T08:10:25+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements