Numpy char.replace() Function



The Numpy char.replace() function allows for the replacement of a specified substring with a new substring in each string element of an array. It operates element-wise, meaning that the replacement occurs in each string within the array.

We can optionally limit the number of replacements by specifying the count parameter. This function is useful for efficiently modifying text data across an array of strings by ensuring consistent replacements throughout the dataset.

Syntax

Following is the syntax of Numpy char.replace() function −

char.replace(a, old, new, count=-1)

Parameters

Following are the parameters of Numpy char.replace() function −

  • a( array-like of str or unicode): The input array containing strings in which the replacement will occur.

  • old (str): The substring that we want to replace.

  • new (str): The input array containing strings in which the replacement will occur.

  • old (str): The substring that will replace the old substring.

  • count (int, optional): The maximum number of occurrences to replace in each string. If not specified, all occurrences are replaced.

Return Value

This function returns an array with the same shape as the input, where the original string is replaced with new defined string.

Example 1

Following is the basic example of Numpy char.replace() function in which we have an array of fruit names and we are replacing letter 'a' with the letter 'o' in each fruit name string −

import numpy as np

arr = np.array(['apple', 'banana', 'cherry'])
result = np.char.replace(arr, 'a', 'o')
print(result)

Below is the output of the basic example of numpy.char.replace() function −

['opple' 'bonono' 'cherry']

Example 2

The char.replace() function allows us to replace the entire string with defined sub string. Here in this example string 'world' is replaced by 'universe' in each element of the array −

import numpy as np
arr = np.array(['hello world', 'world of numpy', 'worldwide'])
print("Original Array:", arr)
result = np.char.replace(arr, 'world', 'universe')
print("Replaced Array:",result)

Here is the output of replacing a string with defined string −

Original Array: ['hello world' 'world of numpy' 'worldwide']
Replaced Array: ['hello universe' 'universe of numpy' 'universewide']

Example 3

If we only want to replace a certain number of occurrences then we can specify the count parameter in the char.replace() function. Following is the example of replacing the first occurrence of 'is' with 'was' in each string −

import numpy as np
arr = np.array(['this is a test', 'this is another test'])
print("Original String:", arr)
result = np.char.replace(arr, 'is', 'was', count=1)
print("Replaced string:",result) 

Here is the output of limiting the number of replaces −

Original String: ['this is a test' 'this is another test']
Replaced string: ['thwas is a test' 'thwas is another test']
numpy_string_functions.htm
Advertisements