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:
# 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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/numpy/python-numpy-string-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics