w3resource

NumPy: Concatenate element-wise two arrays of string


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

Sample Solution:

Python Code:

# Importing the necessary library
import numpy as np

# Creating two NumPy arrays with string elements
x1 = np.array(['Python', 'PHP'], dtype=np.str)
x2 = np.array([' Java', ' C++'], dtype=np.str)

# Displaying the contents of Array1
print("Array1:")
print(x1)

# Displaying the contents of Array2
print("Array2:")
print(x2)

# Concatenating the strings element-wise between x1 and x2 using np.char.add function
new_array = np.char.add(x1, x2)

# Displaying the new array formed by concatenating elements from x1 and x2
print("New array:")
print(new_array)

Sample Input:

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

Sample Output:

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

Explanation:

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: