Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

NumPy multiply() function

In this tutorial, we will cover mutiply() function of the char module in the Numpy library.

The multiply() function is used for repeating the string elements of an ndarray, n number of time, where n can be any integer value. For example, if we have an array with one string element "study", using multiply() function, we can change this string to "studystudy" if we choose the multiplication factor to be 2, and to "studystudystudy" if we choose the factor to be 3, and so on.

This function just like other string functions on Numpy library, performs in an element-wise manner, covering all the array elements.

Syntax of multiply():

The syntax required to use this method is as follows:

numpy.char.multiply(a, i)

The above syntax indicates that multiply() function takes two parameters.

Parameters:

Let us now take a look at the parameters of this function:

  • a
    This parameter indicates an array of strings on which the method will be applied.

  • i
    This parameter indicates the number of times you need to repeat.

Returned Values:

This function will return the array of strings as the utput.

Example 1: With Array having single element

The code snippet is as follows where we will use the multiply() function:

import numpy as np 

arr = np.array(['Study']) 
print("The Original Array is :") 
print(arr) 

i = 5

output = np.char.multiply(arr, i) 
print("\nThe New array is:") 
print(output)


The Original Array is :
['Study']

The New array is:
['StudyStudyStudyStudyStudy']

Example 2: With Array having more than one elements

Let us now take an example where we will have multiple elements in an array and we will apply the method on the same and the code snippet is as follows:

import numpy as np 
 
arr= np.array(['StudyTonight', 'Online', 'Portal']) 
print("The Original Array :") 
print(arr) 

i = 2

output = np.char.multiply(arr, i) 
print("\nThe Resultant array :") 
print(output)


The Original Array :
['StudyTonight' 'Online' 'Portal']

The Resultant array :
['StudyTonightStudyTonight' 'OnlineOnline' 'PortalPortal']

Summary

In this tutorial we learned about the multiply() function of the Numpy Library which is sued with array of strings to repeat the string value of all the data elements of the array.