NumPy: Concatenate element-wise two arrays of string

NumPy String: Exercise-1 with Solution

Write a NumPy program to concatenate element-wise two arrays of string.

Sample Solution:-

Python Code:

import numpy as np
x1 = np.array(['Python', 'PHP'], dtype=np.str)
x2 = np.array([' Java', ' C++'], dtype=np.str)
new_array = np.char.add(x1, x2)
print("new array:")

Sample Input:

(['Python', 'PHP'], dtype=np.str)
([' Java', ' C++'], dtype=np.str)

Sample Output:

['Python' 'PHP']
[' Java' ' C++']
new array:
['Python Java' 'PHP C++']


In the above code –

x1 = np.array(['Python', 'PHP'], dtype=np.str): Create a NumPy array x1 containing two strings 'Python' and 'PHP' with data type np.str.

x2 = np.array([' Java', ' C++'], dtype=np.str): Create another NumPy array x2 containing two strings ' Java' and ' C++' with data type np.str.

new_array = np.char.add(x1, x2): Use the np.char.add function to concatenate corresponding elements of x1 and x2 along the first axis, and return a new NumPy array with the concatenated strings. The resulting array is assigned to the variable new_array.

Pictorial Presentation:

NumPy String: Concatenate element-wise two arrays of string

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: NumPy String Exercises Home.
Next: Write a NumPy program to repeat all the elements three times of a given array of string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Print Imported Modules:

import sys
imported_modules = [m.__name__ for m in sys.modules.values() if m]


We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook