Return a copy of the string with all occurrences of substring old replaced by new in Numpy


To return a copy of the string with all occurrences of substring old replaced by new, use the numpy.char.replace() method in Python Numpy −

  • The 1st parameter is the input array
  • The 2nd parameter is the old string to be replaced
  • The 3rd parameter is the new string to be replaced with the old

If the optional parameter count is given, only the first count occurrences are replaced

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 an array −

arr = np.array(["Welcome to the Jungle", "Jungle Safari"])

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 the string with all occurrences of substring old replaced by new, use the numpy.char.replace() method in Python Numpy −

print("
Result...
",np.char.replace(arr, 'Jungle', 'Club'))

Example

import numpy as np

# Create an array
arr = np.array(["Welcome to the Jungle", "Jungle Safari"])

# 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 the string with all occurrences of substring old replaced by new, use the numpy.char.replace() method in Python Numpy # The 1st parameter is the input array # The 2nd parameter is the old string to be replaced # The 3rd parameter is the new string to be replaced with the old print("
Result...
",np.char.replace(arr, 'Jungle', 'Club'))

Output

Array...
['Welcome to the Jungle' 'Jungle Safari']

Array datatype...
<U21

Array Dimensions...
1

Our Array Shape...
(2,)

Elements in the Array...
2

Result...
['Welcome to the Club' 'Club Safari']

Updated on: 18-Feb-2022

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements