Numpy char.add() Function



The Numpy char.add() function is used to perform element-wise string concatenation. When we give two arrays of strings this function combines corresponding elements from each array by returning a new array of concatenated strings.

If the input arrays are of different shapes then the NumPy broadcasts them to a compatible shape following broadcasting rules. This function is useful for efficiently manipulating and combining string data within NumPy arrays.

Syntax

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

numpy.char.add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])

Parameters

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

  • x1, x2(array_like) − These are the input arrays which has to be added.

  • out(optional) − This is the output array where the result will be placed.

  • where(array_like, optional) − This is the boolean array which specifies where to apply the condition.

  • **kwargs − The parameters such as casting, order, dtype, subok are the additional keyword arguments, which can be used as per the requirement.

Return Value

This function returns the array with the result of sum of x1 and x2.

Example 1

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

import numpy as np

# Define two arrays of strings
a = np.array(['Hello', 'Learners', ','])
b = np.array([' Welcome', ' Tutorialspoint !', 'to'])

# Concatenate the strings element-wise
result = np.char.add(a, b)

print(result)

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

['Hello Welcome' 'Learners Tutorialspoint !' ',to']

Example 2

When using char.add() function with broadcasting we can concatenate arrays of different shapes as long as they are broadcastable to a common shape. Below is the example of it −

import numpy as np

# Define a 1D array of strings
a = np.array(['Hello', 'Goodbye'])

# Define a 2D array of strings
b = np.array(['!', '!!!'])

# Broadcasting the 1D array with the 2D array and concatenating
result = np.char.add(a[:, np.newaxis], b)

print(result)

Here is the output of the above example −

[['Hello!' 'Hello!!!']
 ['Goodbye!' 'Goodbye!!!']]

Example 3

Here this is another example which demonstrates the string concatenation where the strings are concatenated element wise using char.add() function −

import numpy as np 

# Basic concatenation
print('Concatenate two strings:')
print(np.char.add(['hello'], [' xyz']))
print('\n')

# Example with multiple strings
print('Concatenation example:')
print(np.char.add(['hello', 'hi'], [' abc', ' xyz']))

Here is the output of the above example −

Concatenate two strings:
['hello xyz']


Concatenation example:
['hello abc' 'hi xyz']
numpy_string_functions.htm
Advertisements