For each element in a Numpy array, return a copy with the leading and trailing characters removed


To return a copy of an array with the leading and trailing characters removed, use the numpy.char.strip() method in Python Numpy. The "chars" parameter is used to set a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped.

The numpy.char module provides a set of vectorized string operations for arrays of type numpy.str_ or numpy.bytes_.

Steps

At first, import the required library −

import numpy as np

Create a One-Dimensional array of string with some leading and trailing characters −

arr = np.array(['$$Tom$', '$$$$John$$', '$Kate$$', '$Amy$$$$$$$$$', '$Brad$'])

Displaying our array −

print("Array...
",arr)

Get the datatype −

print("
Array datatype...
",arr.dtype)

Get the dimensions of the Array −

print("
Array Dimensions...
",arr.ndim)

Get the shape of the Array −

print("
Our Array Shape...
",arr.shape)

Get the number of elements of the Array −

print("
Elements in the Array...
",arr.size)

To return a copy of an array with the leading and trailing characters removed, use the numpy.char.strip() method. The "chars" parameter is used to set a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped −

print("
Result...
",np.char.strip(arr, '$'))

Example

import numpy as np
# Create a One-Dimensional array of string with some leading and trailing characters
arr = np.array(['$$Tom$', '$$$$John$$', '$Kate$$', '$Amy$$$$$$$$$', '$Brad$'])

# Displaying our array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Number of elements in the Array...
",arr.size) # To return a copy of an array with the leading and trailing characters removed, use the numpy.char.strip() method in Python Numpy # The "chars" parameter is used to set a string specifying the set of characters to be removed. # If omitted or None, the chars argument defaults to removing whitespace. # The chars argument is not a prefix; rather, all combinations of its values are stripped. print("
Result...
",np.char.strip(arr, '$'))

Output

Array...
['$$Tom$' '$$$$John$$' '$Kate$$' '$Amy$$$$$$$$$' '$Brad$']

Array datatype...
<U13

Array Dimensions...
1

Our Array Shape...
(5,)

Number of elements in the Array...
5

Result...
['Tom' 'John' 'Kate' 'Amy' 'Brad']

Updated on: 22-Feb-2022

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements