Signup/Sign In

NumPy add() function

In this tutorial, we will cover add() function of the Numpy library.

The add() function basically returns element-wise string concatenation for two arrays.

Note: If you want to concatenate two arrays then both arrays needs to be of the same shape.

Syntax of add():

The syntax required to use this function is as follows: m1

numpy.char.add(x1, x2)

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

Parameters:

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

  • x1
    This parameter indicates the first array to be concatenated (and it is concatenated at the beginning)

  • x2
    This parameter indicates the second array to be concatenated (and it is concatenated at the end)

Returned Values:

This method will return an output array of either string_ or unicode_ which depends on input types of the same shape as x1 and x2.

Example 1:

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

import numpy as np 

x1 = ['Hello'] 
x2 = ['StudyTonight!'] 
print("The Input arrays are : ") 
print(x1) 
print(x2) 

result = np.char.add(x1, x2) 
print("\nThe Resultant concatenated array is :") 
print(result)


The Input arrays are :
['Hello']
['StudyTonight!']

The Resultant concatenated array is :
['HelloStudyTonight!']

Example 2:

Now we will apply this function on two arrays that contain multiple elements and will see the output:

import numpy as np 

x1 = ['Welcome', 'to', 'StudyTonight'] 
x2 = ['Best Place', 'Forlearning', 'Coding'] 
print("The Input arrays are : ") 
print(x1) 
print(x2) 

result = np.char.add(x1, x2) 
print("\nThe Resultant concatenated array is :") 
print(result)


The Input arrays are :
['Welcome', 'to', 'StudyTonight']
['Best Place', 'Forlearning', 'Coding']

The Resultant concatenated array is :
['WelcomeBest Place' 'toForlearning' 'StudyTonightCoding']

Summary

In this tutorial, we covered the add() function of the Numpy library which can be used to concatenate strings in two given arrays, which is a good usecase, if you have two or more arrays that you want to merge.



About the author:
Aspiring Software developer working as a content writer. I like computer related subjects like Computer Networks, Operating system, CAO, Database, and I am also learning Python.