Numpy char.multiply() Function



The Numpy char.multiply() function which is used for element-wise string repetition. It allows us to repeat strings in an array by a specified number of times, effectively by multiplying each string by the given integer.

This function can be particularly useful for generating repeated patterns or expanding string data in arrays. This function takes two parameters namely, the input array and the number. The number parameter must be a non-negative integer. If it's zero, the result will be an array of empty strings. If it's negative, it raises an error.

This function works with broadcasting rules which means we can also handle arrays of different shapes as long as they are broadcastable.

Syntax

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

numpy.char.multiply(a, number)

Parameters

Below are the parameters of the Numpy char.multiply() function −

  • a(array_like): The input array of strings or a single string.

  • number: An integer specifying how many times to repeat each string in the array.

Return Value

This function returns the array which has the same shape as the input array with each string element repeated as specified.

Example 1

Following is the basic example of Numpy char.multiply() function. Here in this example we are concatenating the strings element-wise −

import numpy as np

# Define an array of strings
a = np.array(['Hello', 'World'])

# Repeat each string 3 times
result = np.char.multiply(a, 3)
print(result)

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

['HelloHelloHello' 'WorldWorldWorld']

Example 2

This example shows how char.multiply() handles strings of different lengths by applying the repetition factor to each string individually. Below is the example of it −

import numpy as np

# Define an array of strings with different lengths
a = np.array(['A', 'BC', 'DEF'])

# Repeat each string 4 times
result = np.char.multiply(a, 4)
print(result)

Here is the output of the above example −

['AAAA' 'BCBCBCBC' 'DEFDEFDEFDEF']

Example 3

When we repeat strings zero times, the result is an array of empty strings and in the same way Negative repetition is invalid and will raise an error because repeating a string a negative number of times doesn't conceptually make sense. Here is the example −

import numpy as np

# Define an array of strings
a = np.array(['Python', 'NumPy'])

# Repeat each string 0 times
result_zero = np.char.multiply(a, 0)
print(result_zero)

Below is the output of zero repetition −

['' '']
numpy_string_functions.htm
Advertisements